如何检查在PHP类中是否定义了常量?
class Foo {
const BAR = 1;
}类常量是否有类似于property_exists()或method_exists()的东西?或者我可以直接用defined("Foo::BAR")
发布于 2014-06-11 09:26:00
是的,只需在常量名称前面使用类名:
defined('SomeNamespace\SomeClass::CHECKED_CONSTANT');发布于 2014-06-11 09:24:55
您可以检查是否用以下代码定义了常量:
<?php
if(defined('className::CONSTANT_NAME')){
//defined
}else{
//not defined
}发布于 2018-06-05 10:23:16
你有三种方法可以做到:
定义()
PHP >= 4-最具追溯性的兼容方式
$class_name = get_class($object); // remember to provide a fully-qualified class name
$constant = "$class_name::CONSTANT_NAME";
$constant_value = defined($constant) ? $constant : null;Note:在(可能来自PHP7.1)上使用defined()将引发错误:“无法访问私有const”。同时使用ReflectionClass或ReflectionClassConstant也可以。
ReflectionClass
PHP >= 5
$class_reflex = new \ReflectionClass($object);
$class_constants = $class_reflex->getConstants();
if (array_key_exists('CONSTANT_NAME', $class_constants)) {
$constant_value = $class_constants['CONSTANT_NAME'];
} else {
$constant_value = null;
}ReflectionClassConstant
PHP7.1.0 >=
$class_name = get_class($object); // fully-qualified class name
try {
$constant_reflex = new \ReflectionClassConstant($class_name, 'CONSTANT_NAME');
$constant_value = $constant_reflex->getValue();
} catch (\ReflectionException $e) {
$constant_value = null;
}没有更好的办法了。取决于您的需求和用例。
https://stackoverflow.com/questions/24159178
复制相似问题