php 检查类常量是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24159178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a class constant exists
提问by Martin Majer
How can I check if a constant is defined in a PHP class?
如何检查 PHP 类中是否定义了常量?
class Foo {
const BAR = 1;
}
Is there something like property_exists()
or method_exists()
for class constants? Or can I just use defined("Foo::BAR")
?
是否有类似property_exists()
或method_exists()
用于类常量的东西?或者我可以使用defined("Foo::BAR")
吗?
采纳答案by Savageman
Yes, just use the class name in front of the constant name.
是的,只需在常量名前使用类名。
回答by Daan
You can check if a constant is defined with the code below:
您可以检查是否使用以下代码定义了常量:
<?php
if(defined('className::CONSTANT_NAME')){
//defined
}else{
//not defined
}
回答by Kamafeather
You have 3 ways to do it:
你有 3 种方法来做到这一点:
defined()
定义()
[PHP >= 4 - most retro-compatible way]
[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;
ReflectionClass
反射类
[PHP >= 5]
[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
反射类常量
[PHP >= 7.1.0]
[PHP >= 7.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;
}
There is no real better way. Depends on your needs and use case.
没有真正更好的方法。取决于您的需求和用例。
回答by quant2016
You can use that function:
您可以使用该功能:
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;
}
Or alternative version using ReflectionClass
或者使用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;
}