Php检查是否声明了静态类


6

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

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

在后面的代码如何检查:

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

,所以我不明白: 致命错误:类“鲍勃”在file.php上未找到线3

13

您还可以检查,具体的方法的存在,即使没有实例化类

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

如果你想多走一步,并确认“开心辞典”实际上是静态的,使用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 
    } 
} 

8

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

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