开发者

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

开发者 https://www.devze.com 2023-03-08 20:07 出处:网络
If objects are passed by reference in PHP5, then why $foo below doesn\'t change? $foo = array(1, 2, 3);

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


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"


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.


Passing by reference not the same as assign.


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.

0

精彩评论

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