返回一個常量的值

constant

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

constant返回一個常量的值

說明

constant(string $name): mixed

返回 name 對應的常量的值。

當你不知道常量名,卻需要獲取常量的值時,constant() 就很有用了。也就是說,常量名儲存在一個變數里,或者由函式返回時。

該函式也適用 類常量

參數

name

常量名。

返回值

返回常量的值。

錯誤/異常

如果常量未定義,會拋出 Error 異常。 在 PHP 8.0.0 之前,會產生一個 E_WARNING 級別的錯誤。

更新日誌

版本 說明
8.0.0 如果常量未定義,constant() 現在會拋出 Error 異常。以前會產生一個 E_WARNING 級別的錯誤並返回 null

範例

示例 #1 constant() 的例子

<?php

define
("MAXSIZE"100);

echo 
MAXSIZE;
echo 
constant("MAXSIZE"); // 和上行一樣


interface bar {
    const 
test 'foobar!';
}

class 
foo {
    const 
test 'foobar!';
}

$const 'test';

var_dump(constant('bar::'$const)); // string(7) "foobar!"
var_dump(constant('foo::'$const)); // string(7) "foobar!"

?>

參見

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *