Search code examples
phpoopmagic-methods

Why is my __clone() not working as expected?


So I am using the code below in one of my PHP classes (within a larger library):

public function __clone() {
    // recreate this class in its' current state
    $new = new \uri(\uri\generate::string($this->object));
    // give it the same origin
    $new->input = $this->input;
    // now send the new instance back
    return $new;
}

In short, I need to recreate the class rather than a traditional clone. However, whenever I use clone, it is still returning a regular clone rather than a new instance.

I need to make a new instance because of how reference variables are used within the class.

--

My testing script:

$uri1 = new uri('example.com');
$uri2 = clone $uri1;

$uri2->host = 'google.com';

// __toString() returns the URI in its' current state
echo $uri1.PHP_EOL.$uri2;

The expected output of the test:

example.com
google.com

The actual output of the test:

google.com
google.com

 

My Question: What am I doing wrong?

I am using PHP 5.5.6


For those who need complete context see the link below (lines 145 to 152). Be warned, there is a lot.

The library in question


Solution

  • From the doc

    When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.

    void __clone ( void ) Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

    So what you need to do is

    public function __clone() {
        // clone properties that needs cloning (no referancing)
    }