在所有 PHP 手册中,它都说 null
、true
和 false
是内部值。但是,它没有说明为什么它们可以用反斜杠编写:\null
、\false
、\true
。
PHP 中的null
、false
和true
到底是什么?
常数还是解释器的一些技巧?
最佳答案
null
、false
和 true
在 PHP 中定义为常量。反斜杠表示 global namespace ,因此您可以像这样为这些常量指定完整的命名空间:\null
。这不是必需的,因为所有常量都是全局常量(使用 const
定义的除外)。
Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope. - PHP Manual on Constants
函数和常量不需要有全限定名。这与 classes which must be specified with their namespace 形成对比例如\异常
。
For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist. - PHP Manual on namespace fallback
编辑
null
、false
和 true
是 PHP 中非常特殊的常量。它们是唯一仍然明确 “不区分大小写” 的。我把它放在引号中的原因是因为实际的常量名称被定义为 NULL
、FALSE
、TRUE
,除了...它实际上不是。它是小写的:
define('TRUE', 'foo'); // works
define('True', 'bar'); // works too, even in combination with the first one
define('true', 'abc'); // Notice: Constant true already defined
var_dump(constant('TRUE')); // string 'foo'
var_dump(constant('True')); // string 'bar'
var_dump(constant('true')); // boolean true
如果您删除 define()
-s,那么即使您使用 constant('True')
,所有常量也会指向 bool 值。 - https://ideone.com/CZSwiX
PHP 手册指出:
To specify a boolean literal, use the constants TRUE or FALSE. Both are case-insensitive.
您可能会问自己,这些常量的值是多少?如果你执行var_dump(TRUE);
,结果将是bool(true)
,如果你执行echo true;
,它会打印出1
。它们在 PHP 源代码中的定义是什么? Here is the answer :
REGISTER_MAIN_BOOL_CONSTANT("TRUE", 1, CONST_PERSISTENT);
REGISTER_MAIN_BOOL_CONSTANT("FALSE", 0, CONST_PERSISTENT);
REGISTER_MAIN_NULL_CONSTANT("NULL", CONST_PERSISTENT);
更有趣的是,他们真的被当作了special constants并且不能被用户重新定义(其他预定义常量可以在它们自己的命名空间中使用 const
重新定义)。因此,我认为,出于所有意图和目的,您不仅可以将这 3 个视为常量,还可以将其视为类似于保留关键字的特殊值。目前它们在 PHP 中仍然作为不区分大小写的 hack 实现,但作为 commit 中的评论@NikiC 表示:“将来我们可能会将它们从常量转换为保留关键字。”
有趣的事实:直到 PHP 7 true
、false
和 null
都不是保留关键字,因此您可以 try something like this :
class TRUE {
const int = 'This is the truest of the integers';
}
var_dump(TRUE::int);
长话短说:
访问 \null
、\false
和 \true
是有效的,因为它们在内部被定义为特殊常量,并且 PHP 中的所有常量都在全局命名空间。
关于php - 为什么null可以写成反斜杠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55707481/