检查是否定义了常数

简单检查

要检查是否定义了常量,请使用 defined 函数。请注意,此函数不关心常量的值,它只关心常量是否存在。即使常数的值是 nullfalse,该函数仍将返回 true

<?php

define("GOOD", false);

if (defined("GOOD")) {
    print "GOOD is defined" ; // prints "GOOD is defined"

    if (GOOD) {
        print "GOOD is true" ; // does not print anything, since GOOD is false
    }
}

if (!defined("AWESOME")) {
   define("AWESOME", true); // awesome was not defined. Now we have defined it 
}

请注意,常量只有在你定义它的行之后才会代码中变为可见

<?php

if (defined("GOOD")) {
   print "GOOD is defined"; // doesn't print anyhting, GOOD is not defined yet.
}

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); // pretty large list

要仅获取应用程序定义的常量,请在脚本的开头和结尾调用函数(通常在引导过程之后):

<?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',
) 
*/

它有时对调试很有用