Reference to static method in PHP?

前端 未结 8 2420
伪装坚强ぢ
伪装坚强ぢ 2021-02-18 18:20

In PHP, I am able to use a normal function as a variable without problem, but I haven\'t figured out how to use a static method. Am I just missing the right syntax, or is this

8条回答
  •  一生所求
    2021-02-18 19:19

    Coming from a javascript background and being spoiled by it, I just coded this:

    function staticFunctionReference($name)
    {
        return function() use ($name)
        {
            $className = strstr($name, '::', true);
            if (class_exists(__NAMESPACE__."\\$className")) $name = __NAMESPACE__."\\$name";
            return call_user_func_array($name, func_get_args());
        };
    }
    

    To use it:

    $foo = staticFunctionReference('Foo::bar');
    $foo('some', 'parameters');
    

    It's a function that returns a function that calls the function you wanted to call. Sounds fancy but as you can see in practice it's piece of cake.

    Works with namespaces and the returned function should work just like the static method - parameters work the same.

提交回复
热议问题