Passing static methods as arguments in PHP

前端 未结 7 1424
温柔的废话
温柔的废话 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条回答
  •  猫巷女王i
    2021-02-02 08:20

    Let my try to give a thorough example...

    You would make a call like this:

    myFunction('Namespace\\MyClass', 'staticMethod');
    

    or like this (if you have arguments you want to pass):

    myFunction('Namespace\\MyClass', 'staticMethod', array($arg1, $arg2, $arg3));
    

    And your function to receive this call:

    public static function myFunction($class, $method, $args = array())
    {
        if (is_callable($class, $method)) {
            return call_user_func_array(array($class, $method), $args);
        }
        else {
            throw new Exception('Undefined method - ' . $class . '::' . $method);
        }
    }
    

    Similiar technique is commonly used in the Decorator Pattern in php.

提交回复
热议问题