親愛なるコミュニティへのご挨拶、
各オブジェクトへの参照の静的配列を介して内部的にすべてのインスタンスを追跡するクラスを作成しようとしています。
# 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 />';
}
}
しかし$_register
、メイン スクリプトを変更しようとすると、次のようになります。
#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'
それでも「0 : hihi」が出力されます。Avar_dump( MyObject::$_register[0] )
は NULL に設定されていることを示しましたが、参照する必要がある MyObject は依然として同じインスタンスを指しています。
PHP の参照を理解しようとしていますが、この動作は私にとって予想外でした。誰か説明してくれませんか。
アドバイスありがとう
PS: C++/Qt を少し試してみる前に、参照/ポインターの使用方法の違いにめまいがしました。