Php Check If a Static Class is Declared

后端 未结 2 653
轮回少年
轮回少年 2020-12-31 18:18

How can i check to see if a static class has been declared? ex Given the class

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


        
相关标签:
2条回答
  • 2020-12-31 18:48

    You can also check for existence of a specific method, even without instantiating the class

    echo method_exists( bob, 'yippie' ) ? 'yes' : 'no';
    

    If you want to go one step further and verify that "yippie" is actually static, use the Reflection API (PHP5 only)

    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();
    }
    

    or, you could combine the two approaches

    if ( method_exists( bob, 'yippie' ) )
    {
        $method = new ReflectionMethod( 'bob::yippie' );
        if ( $method->isStatic() )
        {
            // verified that bob::yippie is defined AND static, proceed
        }
    }
    
    0 讨论(0)
  • bool class_exists( string $class_name [, bool $autoload ])

    This function checks whether or not the given class has been defined.

    0 讨论(0)
提交回复
热议问题