Home > Backend Development > PHP Tutorial > Does Assignment by Reference Affect Object Modification in PHP?

Does Assignment by Reference Affect Object Modification in PHP?

Mary-Kate Olsen
Release: 2024-10-22 07:22:02
Original
888 people have browsed it

Does Assignment by Reference Affect Object Modification in PHP?

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>
Copy after login

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>
Copy after login

The output for the above code is expected to be:

Foo #5
My value has now changed
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template