Alex
Alex

Reputation: 68406

Passing by reference; why is the original object not changed?

If objects are passed by reference in PHP5, then why $foo below doesn't change?

$foo = array(1, 2, 3);
$foo = (object)$foo;

$x = $foo;            // $x = &$foo makes $foo (5)!
$x = (object)array(5);

print_r($foo); // still 1,2,3

so:

Passing by reference not the same as assign.

then why $foo below is (100, 2, 3) ?

$foo = array('xxx' => 1, 'yyy' => 2, 'zzz' => 3);
$foo = (object)$foo;

$x = $foo;            
$x->xxx = 100;

print_r($foo);

Upvotes: 5

Views: 242

Answers (4)

Tadeck
Tadeck

Reputation: 137310

At first you create an object by casting array into object. Then you create variable and pass that object by reference. But it does not work, because after that you assign some other object (casted from new array) into that second variable.

The result is that the reference changed to the second object, the first object itself was not changed.

See more details on the Objects and References.

Upvotes: 0

Bob Fanger
Bob Fanger

Reputation: 29897

The problem lies here:

$x = $foo;   
$x = (object)array(5);

On the first rule $x is referenced to $foo; editing $x wil also edit $foo;
(this is called "assign by reference", not "pass by reference" *1)

$x->myProperty= "Hi";

Will cause $foo to also have a property "myProperty".

But on the next line you reference $x to a new object.
Effectively unreferencing $x from $foo, all changes you make to $x won't propogate to $foo.


*1: When you call a function, the objects you pass to the functions are (in php5) "passed by reference"

Upvotes: 5

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

Not only are objects passed by reference; they are also assigned by reference (which is what you're actually talking about):

An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5.

However, in your first example, you're performing a cast operation. This entails a copy:

If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.

Arrays have their own type in PHP, and are not objects; thus the above rule applies.

Upvotes: 2

gaRex
gaRex

Reputation: 4215

Passing by reference not the same as assign.

Upvotes: 1

Related Questions