PHP的检查,如果静态类被声明(Php Check If a Static Class is Dec

2019-06-28 04:53发布

如何检查,看是否有静态类已申报? 当然考虑到班级

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

后来在代码如何检查:

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

所以我不明白:致命错误:类“鲍勃”在file.php没有发现第3行

Answer 1:

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

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

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


Answer 2:

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

此功能检查给定的类是否已经被定义。



文章来源: Php Check If a Static Class is Declared