在 PHP 中,const 和 define 都可以用来定义常量。但二者之间有什么区别呢?
const 是在编译阶段定义的,define 是在运行时定义的。 因此,const 不可以有条件的定义,但是 define 可以。
if (...) {
const FOO = 'BAR'; //非法的
}
//然而
if (...) {
define('FOO', 'BAR');//合法的
}
const 只能接受静态标量(数字,字符串或者像 true、false、null、__FILE__等其他常量),而 define 接受任何表达式。不过从 PHP 5.6 开始,const 也开始支持表达式。
const 采用普通的常量名称,而 define 接受任何表达式作为名称。他可以做这样用:
for ($i = 0; $i < 32; ++$i) {
define('BIT_' . $i, 1 << $i);
}
define('FOO', 'BAR', true);
echo FOO; // BAR
echo foo; // BAR
namespace A\B\C;
// 比如要设置 A\B\C\FOO:
const FOO = 'BAR';
define('A\B\C\FOO', 'BAR');
最后,请记住 const 可以在类和接口中定义类常量或者接口常量,但是 define 不能这样做 。
class Foo {
const BAR = 2; // 合法
}
class Baz {
define('QUX', 2); // 非法
}
除非你需要根据条件和表达式来定义常量,否则使用 const 而不是 define - 只是为了便于阅读!
翻译自 define() vs const,版权归原作者所有。
暂时没有留言