tags:

views:

24

answers:

2

If I have a PHP class such as this one:

class A
{
    public static function Method()
    {
        return "x";
    }
}

I know that I can access this with:

echo A::Method();

But how would I go about creating a function reference to this method? I tried something like this:

$func = "A::Method";
echo $func();

But it gives me a run-time error. So, is this possible in PHP? If so, how? Thanks! :)

A: 

Class methods or object methods are called differently than normal functions. Use call_user_func or call_user_func_array:

call_user_func(array('A', 'Method'));
call_user_func('A::Method'); // As of 5.2.3
Gumbo
+1  A: 

Two options:

  • call_user_func("A::Method");
  • $func = function () { return A::Method(); }; echo $func()

It's planned (but it's subjected to change) to be able to do this with reflection in the next version of PHP:

$srm = new ReflectionMethod('A::Method');
$func = $srm->getClosure();
$func();
Artefacto
Thanks, this answered my question. :)
SpikeX