要检查是否定义了常数,请使用defined函数。请注意,此函数并不关心常量的值,它仅关心常量是否存在。即使常量的值为null或false函数仍将返回true。
<?php define("GOOD", false); if (defined("GOOD")) { print "GOOD is defined" ; // prints "GOOD is defined" if (GOOD) { print "GOOD is true" ; // 不打印任何内容,因为GOOD为假 } } if (!defined("AWESOME")) { define("AWESOME", true); //真棒没有定义。现在我们已经定义了 }
请注意,只有在定义常量的行之后,常量才会在代码中“可见” :
<?php if (defined("GOOD")) { print "GOOD is defined"; // 不打印任何内容,尚未定义好。 } define("GOOD", false); if (defined("GOOD")) { print "GOOD is defined"; // prints "GOOD is defined" }
要获取所有定义的常量,包括由PHP创建的常量,请使用get_defined_constants函数:
<?php $constants = get_defined_constants(); var_dump($constants); // 很大的清单
要仅获取由您的应用定义的常量,请在脚本的开头和结尾处调用函数(通常在引导过程之后):
<?php $constants = get_defined_constants(); define("HELLO", "hello"); define("WORLD", "world"); $new_constants = get_defined_constants(); $myconstants = array_diff_assoc($new_constants, $constants); var_export($myconstants); /* Output: array ( 'HELLO' => 'hello', 'WORLD' => 'world', ) */
有时对调试很有用