1
for($i = 0; $i < count($prices); $i++){
error_log($prices[$i]->anObjectVariable);
}

or

foreach ($prices as $price){
error_log($price->anObjectVariable);
}

None of these seems to work, here are the errors I get:

PHP Notice:  Undefined property: price::$anObjectVariable

this is the code which I use to prepare the object(s) and the array.

class price {

    public $anObjectVariable;

}

$prices = array();
    $p = new price();
    $p->anObjectVariable = "PRINT ME IN ERROR LOG!";
    array_push($prices, $p);
10
  • So, what's the question itself? Commented Mar 21, 2013 at 17:06
  • 1
    @metal_fan Presumably "why does PHP say that this property is not defined when it is part of the class definition." Commented Mar 21, 2013 at 17:06
  • 2
    error_log($prices[i]->anObjectVariable); should be error_log($prices[$i]->anObjectVariable);, I guess it's a typo ? Commented Mar 21, 2013 at 17:06
  • @romainberger Perhaps, but that wouldn't explain why the foreach variant also fails. Commented Mar 21, 2013 at 17:07
  • 1
    Have you tried var_dump($prices) and/or any other debugging? Commented Mar 21, 2013 at 17:07

2 Answers 2

4

I just tested it locally and the following code works fine if you define $prices as an array before you use it.

class price {

    public $anObjectVariable;

}

$prices = array();
$p = new price();
$p->anObjectVariable = "PRINT ME IN ERROR LOG!";
array_push($prices, $p);

for($i = 0; $i < count($prices); $i++){
    echo($prices[$i]->anObjectVariable);
}

Are you actually testing the code you show us above (i.e. the one I just posted above) or are you working on a derivative? Can you confirm that this exact snippet above works for you correctly?

Sign up to request clarification or add additional context in comments.

8 Comments

Is correct. Php throws a warning if the array doesn't already exist. OP, dial up the error reporting.
no, in the code on which I'm working $prices is passed in as a variable in a function but it is declared, I'm sure of that.
Yeah, I'm sure of it because if I var_dump($prices) right before the loop I can see the array correctly...
Well, then again, I ask: Can you copy the code above and see if that one works for you. Because if it does, then you might have the first clue why your other code doesn't work.
Got the error! I've solved the typo of $i just to see there was another one. Fixed, thanks!
|
2

Then if it's not a typo

for ($i = 0; $i < count($prices); $i++) {
    error_log($prices[$i]->anObjectVariable);
}

should work

1 Comment

I tried with you code and it worked... which one of the errors do you get with this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.