1

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 ?

1 Answer 1

3

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

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

4 Comments

So I must just remember this behaviour "as is"?
Or, you might want to read this: php.net/manual/en/language.oop5.references.php
Where I can find information about my question in this manual?
> 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.

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.