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! :)
Static member functions have a class scope and they do not have access to the this pointer of the class.
The 'this' pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. 'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).
Static member functions do not work on an object, so the this pointer is not needed.
What should be used to point to a static class member? Explanation: Normal pointer is sed to point to a static class member.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With