【问题标题】:Need help with php5.3 static inheritance在php5.3静态继承方面需要帮助
【发布时间】:2011-05-29 01:54:28
【问题描述】:

在 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){}

这两个不起作用。

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

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

现在我需要打电话

【问题讨论】:

    标签: php function static php-5.3


    【解决方案1】:

    试试

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

    http://php.net/get_called_class

    【讨论】:

      【解决方案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();
      }
      

      【讨论】:

      • is_callable(array('static', 'func')) 工作正常。我担心如果 'func' 不存在,那么 is_callable 可能至少会引发一个警告,即未定义变量,但事实并非如此。如果 func 函数不存在,则返回 false,这很好。
      猜你喜欢
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 2012-02-17
      • 2011-01-27
      • 2014-02-06
      • 2017-11-02
      相关资源
      最近更新 更多