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!"

?>

参见

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top