Determining Object Assignment in PHP
In PHP programming, objects can be assigned by either value or reference. This distinction affects how changes made to an object reflect in other parts of the code.
Let's consider the following code:
<code class="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"); } }</code>
The question arises: when the "Bar::test()" method is executed, will modifying "foo # 5" in the array of "Foo" objects affect the actual "foo # 5" object itself or create a separate local variable "testFoo"?
Answer:
To determine the answer, we can execute the code and observe the output:
<code class="php">$b = new Bar; echo $b->getFoo(5)->value; $b->test(); echo $b->getFoo(5)->value;</code>
The output for the above code is expected to be:
Foo #5 My value has now changed
This indicates that the change made to the "testFoo" object affects the actual "foo # 5" object in the array. This behavior is attributed to the concept of "assignment by reference" in PHP 5, which applies to objects by default.
Implications:
Assignment by reference ensures that subsequent changes to an object are reflected throughout the code. However, if you desire to create an independent copy of an object, you can utilize the "clone" keyword to perform a value-based assignment.
The above is the detailed content of Does Assignment by Reference Affect Object Modification in PHP?. For more information, please follow other related articles on the PHP Chinese website!