PHP5+引進$GLOBALS延遲初始化的概念

來源:互聯網
上載者:User
PHP5+引進$GLOBALS延遲初始化的概念
  作者:zhanhailiang 日期:2013-01-18

今天整理代碼想使用$GLOBALS['_SERVER']來替代$_SERVER來訪問相關的環境變數,總是會報“_SERVER undefined”錯誤。如下用例:

用例1:

 print_r($GLOBALS);

此時輸出中並沒有_SERVER相關資訊:

Array(    [GLOBALS] => Array *RECURSION*    [_POST] => Array        (        )     [_GET] => Array        (        )     [_COOKIE] => Array        (        )     [_FILES] => Array        (        ))

用例2:

 print_r($GLOBALS);print_r($_SERVER);

此時輸出中含有_SERVER相關資訊:

Array(    [GLOBALS] => Array *RECURSION*    [_POST] => Array        (        )     [_GET] => Array        (        )     [_COOKIE] => Array        (        )     [_FILES] => Array        (        )     [_SERVER] => Array        (         ) )

查了下PHP手冊關於$GLOBALS描述,引用therandshow at gmail dot com的評論:

therandshow at gmail dot com
As of PHP 5.4 $GLOBALS is now initialized just-in-time. This means there now is an advantage to not use
the $GLOBALS variable as you can avoid the overhead of initializing it. How much of an advantage that is
I'm not sure, but I've never liked $GLOBALS much anyways.

追根數源,發現PHP5Changelog更新日誌的描述:

Unordered List ItemImproved Zend Engine, performance tweaks and optimizations
Unordered List ItemChanged $GLOBALS into a JIT autoglobal, so it's initialized only if used. (this may affect opcode caches!)

 718 ; When enabled, the SERVER and ENV variables are created when they're first 719 ; used (Just In Time) instead of when the script starts. If these variables 720 ; are not used within a script, having this directive on will result in a 721 ; performance gain. The PHP directives register_globals, register_long_arrays, 722 ; and register_argc_argv must be disabled for this directive to have any affect. 723 ; http://php.net/auto-globals-jit 724 auto_globals_jit = On

終於弄明白了,PHP5+中在開啟auto_globals_jit = On情況下,$_SERVER變數和$_ENV變數不會在指令碼啟動時就建立,而是會在第一次使用$SERVER和$ENV時才會建立。所以就會出現上述兩個用例的情況。

備忘:

實測結論:

auto_globals_jit setting is also affecting $_REQUEST superglobal in 5.3 It is not explicitly stated in documentation.
至少5.3.13版本中開啟auto_globals_jit = On情況下,$_REQUEST也只會在第一次使用時才會建立。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.