2

在 php 5.3 中使用这个静态“继承”有点麻烦,我需要测试静态类中是否存在静态函数,但我需要从父静态类中测试它。

我知道在 php 5.3 中我可以使用 'static' 关键字来模拟 'this' 关键字。我只是找不到测试函数是否存在的方法。

这是一个例子:

// parent class
class A{

// class B will be extending it and may or may not have 
// static function name 'func'
// i need to test for it

    public static function parse(array $a){
        if(function_exists(array(static, 'func'){
            static::func($a);
        }
    }
}

class B extends A {
    public static function func( array $a ){
        // does something
    }
}

所以现在我需要执行B::parse(); 的想法是,如果子类有函数,就使用它,否则就不会使用。

我试过了:

function_exists(static::func){}
isset(static::func){}

这2个不起作用。

任何想法如何做到这一点?顺便说一句,我知道传递 lambda 函数作为解决方法的可能性,在我的情况下这不是一个选项。

我有一种感觉,有一个非常简单的解决方案,我现在想不出。

现在我需要打电话

4

2 回答 2

2

您不能function_exists用于类和对象(方法),只能用于函数。您必须使用method_existsis_callableisset仅适用于变量。另外,static不模拟$this,它们是完全不同的两个东西。

话虽如此,在这种特定情况下,您必须使用is_callable带引号的static关键字:

if (is_callable(array('static', 'func'))) {
    static::func();
}

或者...

if (is_callable('static::func')) {
    static::func();
}
于 2010-12-21T21:07:38.207 回答
0

尝试

public static function parse(array $a){
    if(function_exists(array(get_called_class(), 'func') {
/*...*/

http://php.net/get_call_class

于 2010-12-21T21:05:08.167 回答