Php检查是否声明静态类

时间:2008-09-23 20:41:15

标签: php object static

我如何检查是否已声明静态类? 前 鉴于班级

class bob {
    function yippie() {
        echo "skippie";
    }
}

稍后在代码中如何检查:

if(is_a_valid_static_object(bob)) {
    bob::yippie();
}

所以我没有得到: 致命错误:第3行的file.php中找不到类'bob'

2 个答案:

答案 0 :(得分:16)

即使没有实例化类

,您也可以检查特定方法是否存在
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
    }
}

答案 1 :(得分:8)

bool class_exists( string $class_name [, bool $autoload ])

  

此函数检查是否已定义给定的类。

相关问题