Press "Enter" to skip to content

PHP: self and clone

I recently had to make a PHP class (let’s call it “class_A”) which returned an array of itself (to return multiple search results). All well and good and I used “$object=new self();” to do so like this:


class class_A {
public $setting;

public function doSomething() {
$toReturn=Array();
for ($i=1;$i<100;$i++) { $object=new self(); $object->setting=$i;
Array_push($toReturn,$object);
return $object;
}
}

Calling $class_A->doSomething() then returns 100 “class_A” objects.

However, I then needed to extend the PHP class (let’s call this class_B – declared with “class class_B extends class_A”) to take into account additional settings and I fully expected $object to be a new copy of class_B (as class B is technically the class being run).

Nope, it doesn’t work like that. I ended up with $object being class_A . I had to modify the code to change:
$object=new self();
to:
$object=clone $this;
which then allowed $class_B->doSomething(); to return 100 class_B objects.

Annoying, but something to remember!