檢查是否定義了常數

簡單檢查

要檢查是否定義了常量,請使用 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',
) 
*/

它有時對除錯很有用