哪位大神能從記憶體的角度解釋下 php 官方手冊上的這個例子,我是個初級
PHPer
搞不太明白,請前輩不吝賜教,晚輩不勝感謝!
最好能下面代碼運行時的記憶體
的情況說明下。
類似的行為也適用於 static 語句。引用並不是靜態地儲存的:
function &get_instance_ref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // 將一個引用賦值給靜態變數 $obj = &new stdclass; } $obj->property++; return $obj;}function &get_instance_noref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // 將一個對象賦值給靜態變數 $obj = new stdclass; } $obj->property++; return $obj;}$obj1 = get_instance_ref();$still_obj1 = get_instance_ref();echo "\n";$obj2 = get_instance_noref();$still_obj2 = get_instance_noref();
以上常式會輸出:
Static object: NULLStatic object: NULLStatic object: NULLStatic object: object(stdClass)(1) {["property"]=>int(1)}
上例示範了當把一個引用賦值給一個靜態變數時,第二次調用 &get_instance_ref() 函數時其值並沒有被記住。
本例出處:http://php.net/manual/en/language.variables.scope.php
回複內容:
哪位大神能從記憶體的角度解釋下 php 官方手冊上的這個例子,我是個初級 PHPer
搞不太明白,請前輩不吝賜教,晚輩不勝感謝!
最好能下面代碼運行時的記憶體
的情況說明下。
類似的行為也適用於 static 語句。引用並不是靜態地儲存的:
function &get_instance_ref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // 將一個引用賦值給靜態變數 $obj = &new stdclass; } $obj->property++; return $obj;}function &get_instance_noref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // 將一個對象賦值給靜態變數 $obj = new stdclass; } $obj->property++; return $obj;}$obj1 = get_instance_ref();$still_obj1 = get_instance_ref();echo "\n";$obj2 = get_instance_noref();$still_obj2 = get_instance_noref();
以上常式會輸出:
Static object: NULLStatic object: NULLStatic object: NULLStatic object: object(stdClass)(1) {["property"]=>int(1)}
上例示範了當把一個引用賦值給一個靜態變數時,第二次調用 &get_instance_ref() 函數時其值並沒有被記住。
本例出處:http://php.net/manual/en/language.variables.scope.php
用靜態方式調用一個非靜態方法會導致一個 E_STRICT 層級的錯誤。
就像其它所有的 PHP 靜態變數一樣,靜態屬性只能被初始化為文字或常量,不能使用運算式。所以可以把靜態屬性初始化為整數或數組,但不能初始化為另一個變數或函數傳回值,也不能指向一個對象。
出處:http://php.net/manual/zh/language.oop5.static.php
所以global和static不用使用引用賦值,這是由php解譯器決定的。