Greetings dear Community,
I am trying to write a class which keeps track of all instances internally via a static array of references to each object:
# MyObject.php
class MyObject{
public static $_register = array();
public $_id = -1;
public $_value = '';
function __construct( $value ){
$this->_value = $value;
$this->_id = count( self::$_register );
self::$_register[ $this->_id ] =& $this; // I also tried '= &$this'
}
function foo(){ // outputs 'id : value'
echo $this->_id.' : ' . $this->_value . '<br />';
}
}
But when I try to alter $_register
in my main script:
#main.php
require_once( 'MyObject.php' );
$test = new MyObject( 'hihi' );
$test->foo(); // outputs '0 : hihi'
MyObject::$_register[0] = NULL;
$test->foo(); // still outputs '0 : hihi'
It still outputs '0 : hihi'. A var_dump( MyObject::$_register[0] )
showed that it's set to NULL, but the should-be-referenced MyObject still points to the same Instance.
I am trying to understand references in PHP and this behaviour was unexpected for me. Could someone please explain it.
Thanks in advice
P.S: Before I tried a little C++/Qt and the difference in usage of references/pointers is making me dizzy.
That's because with unset you'll destroy only reference to object, but not object itself. This may seems odd, but unsetting a reference is treated as destroying reference, not entity to which that reference is pointing.
In PHP, however, reference is NOT a pointer. The big difference is shown in PHP references tutorial. So in common case - no, you can not unset an entity with given reference to it. Remember: PHP references have nothing to do with C-pointers.