Passing static methods as arguments in PHP

前端 未结 7 1422
温柔的废话
温柔的废话 2021-02-02 07:34

In PHP is it possible to do something like this:

myFunction( MyClass::staticMethod );

so that \'myFunction\' will have a reference to the stati

7条回答
  •  时光取名叫无心
    2021-02-02 08:13

    to the question:

    In PHP is it possible to do something like this:

    myFunction( MyClass::staticMethod );

    the answer is yes. you can have the staticMethod() return anonymous function instead. i.e.

    private static function staticMethod()
    {
        return function($anyParameters)
        {
            //do something here what staticMethod() was supposed to do
            // ...
            // ...
            //return something what staticMethod() was supposed to return;
        };
    }
    

    you can then write

    myFunction(MyClass::staticMethod());
    

    but note that () is needed to invoke staticMethod(). This is because it now returns the anonymous function that wraps the job of what you initially wanted your staticMethod() to do.

    This works perfectly fine when staticMethod() is only being passed in as parameter into another function. If you wish to call staticMethod() that directly does the processing, you have to then write

    MyClass::staticMethod()($doPassInParameters);
    

    Note that this may require one extra redundant step to retrieve the function pointer, as compared to when it can work without wrapping it in anonymous function. I only use it to pass as parameter so am not sure of the performance penalty of the extra step. Perhaps negligible ...

提交回复
热议问题