In this code:
<?php class Foo { var $value; function foo($value) { $this->setValue($value); } function setValue($value) { $this->value=$value; } } class Bar { var $foos=array(); function Bar() { for ($x=1; $x<=10; $x++) { $this->foos[$x]=new Foo("Foo # $x"); } } function getFoo($index) { return $this->foos[$index]; } function test() { $testFoo=$this->getFoo(5); $testFoo->setValue("My value has now changed"); } } ?>
When the method Bar::test()
is run and it changes the value of foo # 5 in the array of foo objects, will the actual foo # 5 in the array be affected, or will the $testFoo
variable be only a local variable which would cease to exist at the end of the function?
Object references are passed by value The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.
An object variable is always a reference-type. It's possible for object to "reference" a value-type by the power of boxing.
You can assign an existing object reference to another variable using the Set statement without the New keyword. An assignment using Set does not copy an object. The assigned value is a reference to an object, not the object itself.
With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified.
Why not run the function and find out?
$b = new Bar; echo $b->getFoo(5)->value; $b->test(); echo $b->getFoo(5)->value;
For me the above code (along with your code) produced this output:
Foo #5 My value has now changed
This isn't due to "passing by reference", however, it is due to "assignment by reference". In PHP 5 assignment by reference is the default behaviour with objects. If you want to assign by value instead, use the clone keyword.
You can refer to http://ca2.php.net/manual/en/language.oop5.references.php for the actual answer to your question.
One of the key-points of PHP5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true.
A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP5, 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.
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