PHP检查是否声明了静态类
时间:2020-03-06 14:37:33 来源:igfitidea点击:
如何检查是否已声明静态类?
前任
给定班级
class bob { function yippie() { echo "skippie"; } }
稍后在代码中我如何检查:
if(is_a_valid_static_object(bob)) { bob::yippie(); }
所以我不明白:
致命错误:在第3行的file.php中找不到类'bob'
解决方案
bool class_exists(字符串$ class_name [,bool $ autoload]
)
This function checks whether or not the given class has been defined.
我们也可以检查特定方法的存在,即使不实例化该类
echo method_exists( bob, 'yippie' ) ? 'yes' : 'no';
如果我们想更进一步并验证" yippie"实际上是静态的,请使用Reflection API(仅PHP5)
try { $method = new ReflectionMethod( 'bob::yippie' ); if ( $method->isStatic() ) { // verified that bob::yippie is defined AND static, proceed } } catch ( ReflectionException $e ) { // method does not exist echo $e->getMessage(); }
或者,我们可以将两种方法结合起来
if ( method_exists( bob, 'yippie' ) ) { $method = new ReflectionMethod( 'bob::yippie' ); if ( $method->isStatic() ) { // verified that bob::yippie is defined AND static, proceed } }