函式名:constant() 適用版本:所有 PHP 版本
用法:constant() 函式用於獲取常量的值。它可以接受一個常量名作為引數,並返回該常量的值。
示例 1: 定義一個常量: define('GREETING', 'Hello, world!');
使用 constant() 函式獲取常量的值: echo constant('GREETING'); // 輸出:Hello, world!
示例 2: 常量也可以在名稱空間下使用。在名稱空間中使用 constant() 函式時,需要指定常量所在的名稱空間: namespace MyNamespace;
define('VERSION', '1.0');
echo constant('MyNamespace\VERSION'); // 輸出:1.0
注意事項:
- 如果常量不存在或者未定義,constant() 函式將返回 NULL,並觸發一個 E_WARNING 錯誤。
- 如果需要檢查常量是否被定義,可以使用 defined() 函式。
更多示例及用法請參考 PHP 手冊:https://www.php.net/manual/zh/function.constant.php