Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer to static class member?

Tags:

php

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! :)

like image 636
qJake Avatar asked Aug 09 '10 20:08

qJake


People also ask

Can this pointer access static member of a class?

Static member functions have a class scope and they do not have access to the this pointer of the class.

How do I pass a pointer to a static function?

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).

Why should we not use this pointer with static member function of a class?

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?

What should be used to point to a static class member? Explanation: Normal pointer is sed to point to a static class member.


1 Answers

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();
like image 186
Artefacto Avatar answered Oct 19 '22 11:10

Artefacto