Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 ?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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

share|improve this answer
    
So I must just remember this behaviour "as is"? –  Guy Fawkes May 20 '11 at 13:14
    
Or, you might want to read this: php.net/manual/en/language.oop5.references.php –  Denis May 20 '11 at 13:24
    
Where I can find information about my question in this manual? –  Guy Fawkes May 20 '11 at 13:41
1  
> An object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object. –  Denis May 20 '11 at 14:05
    
Thank you very much. –  Guy Fawkes May 22 '11 at 12:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.