Home >Backend Development >PHP Tutorial >How Does Assignment Behavior Affect Objects in PHP: Value vs. Reference?
Understanding Object Assignment in PHP: Value vs. Reference
When it comes to object assignment in PHP, understanding the difference between value and reference behavior is crucial. PHP can assign objects either by value or by reference.
Original Code Snippet
Consider the following PHP 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>
Question: Assignment Behavior
When the Bar::test() method is executed and 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 that ceases to exist at the end of the function?
Answer: Assignment by Reference
To determine the behavior, let's analyze the given code:
<code class="php">$b = new Bar; echo $b->getFoo(5)->value; $b->test(); echo $b->getFoo(5)->value;</code>
Executing this code produces the following output:
Foo #5 My value has now changed
Explanation
PHP assigns objects by reference by default in version 5. This means that when the foo # 5 object is returned by getFoo(), a reference to the same object is stored in the $testFoo variable.
Consequently, when the setValue() method is called on $testFoo, the actual foo # 5 object in the array is modified, not just a local copy. This is the reason why the value of foo # 5 changes even after the Bar::test() method executes.
Note on Assignment by Value
If desired, you can assign objects by value instead of by reference using the clone keyword:
<code class="php">$testFoo = clone $this->getFoo(5); $testFoo->setValue("My value has now changed");</code>
The above is the detailed content of How Does Assignment Behavior Affect Objects in PHP: Value vs. Reference?. For more information, please follow other related articles on the PHP Chinese website!