如何查看实例化类中是否定义了常量?
我有:
Class foo {
const BAR = 'baz';
}
Run Code Online (Sandbox Code Playgroud)
然后$foo被传递到另一个类中的函数中,在该类中,我检查是否已设置并使用其值(或默认值):
Class abc {
public function xyz($foo)
{
if (defined($foo::BAR)) {
$var = $foo::BAR;
} else {
$var = 'default';
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是无论我做什么,我都无法弄清楚是否定义了常量。它要么已定义并且可以工作,要么没有定义并抛出,FatalError: Undefined class constant 'BAR'然后我们才能到达else。
这些是我已经完成的各种转储(我可以记得)及其结果:
$foo::BAR | string 'baz' (length=3)
$foo->BAR | null
$foo::BAR !== null | boolean true (when set) Error (when unset)
defined($foo::BAR) | boolean false
defined('$foo::BAR') | boolean false
defined("$foo::BAR") | boolean false
defined('BAR', $foo) | Error
Run Code Online (Sandbox Code Playgroud)
如果有帮助,我正在使用Laravel 5.4和PHP 5.6。
用类名而不是对象变量可能更好地工作:
if(defined(get_class($foo).'::BAR')) // Do something
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |