Function pointer to static class member?
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! :)
Two options:
call_user_func("A::Method");
$func = function () { return A::Method(); }; echo $func()
It's planned (but it's subject 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();
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
精彩评论