如何检查PHP类中是否定义了常量?
class Foo {
const BAR = 1;
}
Run Code Online (Sandbox Code Playgroud)
有类似于property_exists()或method_exists()类常量的东西吗?或者我可以使用defined("Foo::BAR")?
Daa*_*aan 69
您可以使用以下代码检查是否定义了常量:
<?php
if(defined('className::CONSTANT_NAME')){
//defined
}else{
//not defined
}
Run Code Online (Sandbox Code Playgroud)
Sav*_*man 27
是的,只需在常量名称前面使用类名.
http://www.php.net/manual/en/function.defined.php#106287
您可以使用该功能:
function constant_exists($class, $name){
if(is_string($class)){
return defined("$class::$name");
} else if(is_object($class)){
return defined(get_class($class)."::$name");
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
或者使用ReflectionClass 的替代版本
function constant_exists($class, $name) {
if(is_object($class) || is_string($class)){
$reflect = new ReflectionClass($class);
return array_key_exists($name, $reflect->getConstants());
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
您有3种方法可以做到:
$class_name = get_class($object); // remember to provide a fully-qualified class name
$constant = "$class_name::CONSTANT_NAME";
$constant_value = defined($constant) ? $constant : null;
Run Code Online (Sandbox Code Playgroud)
$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;
}
Run Code Online (Sandbox Code Playgroud)
$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;
}
Run Code Online (Sandbox Code Playgroud)
没有真正更好的方法。取决于您的需求和用例。
| 归档时间: |
|
| 查看次数: |
24599 次 |
| 最近记录: |