开发者

PHP Foreach on array of objects

开发者 https://www.devze.com 2023-03-07 18:47 出处:网络
Why, if I have array of objects like this: class testClass { private $_x = 10; public function setX($x) {

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 h开发者_运维技巧ave scalar values in array, they can only be modified by ($arr as &$v), $v only by reference ?


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消