2014-02-17 43 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 –