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);
When an object (or built-in type) is passed by reference to a function, the underlying object is not copied. The function is given the memory address of the object itself. This saves both memory and CPU cycles as no new memory is allocated and no (expensive) copy constructors are being called.
Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.
Yes, objects are reference values, it doesn't get copied when passed into a function - and when you mutate it that means you're mutating the single original.
Objects are always passed by reference . That is, when passing an object to a function, the function will act on the same object. If the object changes inside the function, the change will be reflected outside the function. This is an extension of the behavior of assigning an object to a new variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With