2014-02-17 39 views
1

有問題在PHP想,如果有人可以解釋常數:PHP恆裏面IF

這個作品

const _ROOT = 'd:/aphp/www'; 

echo "r="._ROOT; 

爲做到這一點:

if (true) 
     define('_ROOT','d:/aphp/www'); 

echo "r="._ROOT; 

但是這給了錯誤:解析錯誤:語法錯誤,意外T_CONST

if (true) 
    const _ROOT = 'd:/aphp/www'; 

echo "r="._ROOT; 

我使用PHP 5.3.2

回答

6

那是因爲...

const關鍵字必須在頂層範圍

從PHP文件

Note: As opposed to defining constants using define(), constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops or if statements.

Source聲明

+1

謝謝,它隱藏在這裏的「註釋」http://php.net/language.constants.syntax –