Let's consider the following code:
class a {
public $var1;
function disp(){
echo $this->var1;
}
}
$obj1 = new a;
echo '<br/>After instantiation into $obj1:<br/>';
xdebug_debug_zval('obj1');
$obj1->var1 = "Hello ";
echo '<br/><br/>After assigning "Hello" to $obj->var1:<br/>';
$obj1->disp();
echo "<br/><br/>";
xdebug_debug_zval('obj1');
The output:
After instantiation into $obj1:
obj1: (refcount=1, is_ref=0)=class a { public $var1 = (refcount=2, is_ref=0)=NULL }After assigning "Hello" to $obj->var1:
Helloobj1: (refcount=1, is_ref=0)=class a { public $var1 = (refcount=1, is_ref=0)='Hello ' }
One by one:
After instantiation into $obj1:
obj1: (refcount=1, is_ref=0)=class a { public $var1 = (refcount=2, is_ref=0)=NULL }
Why does $obj1->var1 have refcount=2 when there is only one object of class a?
Is it because of how the new operator makes assignment?
PHP does assignment with references. When instantiated with new, no symbol/variable name is associated with that instance. But, the class properties do have names. Is the recount=2 because of this?
If that is the case then a C.O.W (copy on write) has occurred with a shallow copy WRT the class instance. While the properties are still pointing to the zval's of properties created during the instantiation using new.
Now,
After assigning "Hello" to $obj->var1:
Helloobj1: (refcount=1, is_ref=0)=class a { public $var1 = (refcount=1, is_ref=0)='Hello ' }
So, when I assign a value to the property $obj1->var1 a new zval container for that property and hence the refcount=1