Do PHP Objects Use Value or Reference Assignment?

Susan Sarandon
Release: 2024-10-22 07:25:02
Original
827 people have browsed it

Do PHP Objects Use Value or Reference Assignment?

Are Objects in PHP Assigned by Value or Reference?

In PHP, objects are assigned by reference by default. This means that when a variable is assigned an object reference, it points directly to the object in memory. Any changes made to the object through the variable will be reflected in the original object.

Consider the following example:

<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");
    }
}

$b = new Bar;
echo $b->getFoo(5)->value;
$b->test();
echo $b->getFoo(5)->value;</code>
Copy after login

When the Bar::test() method is executed, it changes the value of the fifth object in the array of Foo objects. This change is reflected in the original object, as seen in the output:

Foo #5
My value has now changed
Copy after login

This behavior is due to the assignment of the object reference to the $testFoo variable. The variable points directly to the object, so any modifications made through the variable will be reflected in the original object.

To assign an object by value instead of reference, you can use the clone keyword:

<code class="php">$testFoo = clone $this->getFoo(5);</code>
Copy after login

The above is the detailed content of Do PHP Objects Use Value or Reference Assignment?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!