PHP 检查是否定义了常量
示例
简单检查
要检查是否定义了常数,请使用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',
)
*/有时对调试很有用
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短