我如何检查是否已声明静态类?ex鉴于上课
class bob {
function yippie() {
echo "skippie";
}
}
Run Code Online (Sandbox Code Playgroud)
稍后在代码中如何检查:
if(is_a_valid_static_object(bob)) {
bob::yippie();
}
Run Code Online (Sandbox Code Playgroud)
所以我没有得到:致命错误:在第3行的file.php中找不到类'bob'
Pet*_*ley 16
您还可以检查特定方法是否存在,即使没有实例化该类也是如此
echo method_exists( bob, 'yippie' ) ? 'yes' : 'no';
Run Code Online (Sandbox Code Playgroud)
如果您想更进一步并确认"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();
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以将这两种方法结合起来
if ( method_exists( bob, 'yippie' ) )
{
$method = new ReflectionMethod( 'bob::yippie' );
if ( $method->isStatic() )
{
// verified that bob::yippie is defined AND static, proceed
}
}
Run Code Online (Sandbox Code Playgroud)