代码之家  ›  专栏  ›  技术社区  ›  Joe Lencioni

在PHP中,当动态调用静态方法时,使用forward_static_call_array()而不是call_user_func_array()有什么优势吗?

  •  12
  • Joe Lencioni  · 技术社区  · 15 年前

    具体来说,一个比另一个更有效率吗?

    1 回复  |  直到 12 年前
        1
  •  11
  •   Pascal MARTIN    15 年前

    两者之间至少有两个区别 forward_static_call_array call_user_func_array :

    • 第一个仅存在于PHP5.3之后
    • 第一个必须从类内部调用


    实际上,如果你仔细看一看给定的例子,它似乎就是:你正在使用的类的“上下文” 前向\u静态\u调用\u数组 在被调用的方法中为“keep”。

    考虑到代码的这一部分,这是从给定的示例中派生出来的:

    class A {
        const NAME = 'A';
        public static function test() {
            $args = func_get_args();
            echo static::NAME, " ".join(',', $args)." \n";      // Will echo B
        }
    }
    
    class B extends A {
        const NAME = 'B';
        public static function test() {
            echo self::NAME, "\n";          // B
            forward_static_call_array(array('A', 'test'), array('more', 'args'));
        }
    }
    
    B::test('foo');
    

    您将获得以下输出:

    B
    B more,args
    

    i、 e.从A类中的方法,你“知道”,通过 static::


    现在,如果你试着用同样的方法 call_user_func :

    class B extends A {
        const NAME = 'B';
        public static function test() {
            echo self::NAME, "\n";          // B
            call_user_func_array(array('A', 'test'), array('more', 'args'));
        }
    }
    

    (代码的其余部分不变)

    您将获得以下输出:

    B
    A more,args
    

    注意 A. 前向\u静态\u调用\u数组 ,你没有拿到 ,但是 .

    前向\u静态\u调用\u数组 将静态上下文转发到调用的方法,而 调用用户函数数组