PHP 全域和靜態變數的引用問題?

來源:互聯網
上載者:User
關鍵字 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

回複內容:

哪位大神能從記憶體的角度解釋下 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解譯器決定的。

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.