Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, are there any advantages to using forward_static_call_array() instead of call_user_func_array() when dynamically calling a static method?

Specifically, is one more efficient than the other?

like image 885
Joe Lencioni Avatar asked Feb 26 '10 18:02

Joe Lencioni


1 Answers

There is at leat two differences between forward_static_call_array and call_user_func_array :

  • The first one only exists since PHP 5.3
  • The first one must be called from inside a class

After that, I suppose there is some difference that's related to Late Static Binding, that was introduced with PHP 5.3.


Actually, if you take a closer look at the given example, it seems to be exactly that : the "context" of the class inside which you are using forward_static_call_array is "kept", in the called method.

Considering this portion of code, that's derived from the given example :

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');

You'll get this output :

B
B more,args

i.e. from the method in class A, you "know", via the static:: keyword, that you're "coming from B".


Now, if you try to do the the same thing with 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'));
    }
}

(the rest of the code doesn't change)

You'll get this output :

B
A more,args

Note the A on the second line ! With forward_static_call_array, you didn't get an A, but a B.

That's the difference : forward_static_call_array forwards the static context to the method that's called, while call_user_func_array doesn't.


About your efficiency question : I have no idea -- you'd have to benchmark ; but that's really not the point : the point is that those two functions don't do the same thing.

like image 137
Pascal MARTIN Avatar answered Oct 25 '22 17:10

Pascal MARTIN