Guy Fawkes
Guy Fawkes

Reputation: 2441

PHP Foreach on array of objects

Why, if I have array of objects like this:

class testClass {

    private $_x = 10;

    public function setX($x) {
       $this->_x = $x;
    }

    public function writeX() {
        echo $this->_x . '<br />';
    }

}

$t = array();

for ($i = 0; $i < 10; $i++) {
    $t[] = new testClass();
}

print_r($t);

I can iterate by foreach like this:

foreach ($t as $tt) {
    $tt->y = 7;
    $tt->setX($counter);
    $counter+=100;
}

print_r($t);

Or this:

foreach ($t as &$tt) {
    $tt->y = 7;
    $tt->setX($counter);
    $counter+=100;
}

print_r($t);

And result will be equal? But if i have scalar values in array, they can only be modified by ($arr as &$v), $v only by reference ?

Upvotes: 1

Views: 2246

Answers (1)

Denis de Bernardy
Denis de Bernardy

Reputation: 78571

It depends on whether you're using PHP5 or an earlier version.

In PHP5, same thing because it is an array of objects. (Not the same thing for other types.)

In PHP4, not the same thing. (But then again, the second one will complain about a syntax anyway.)

Upvotes: 3

Related Questions