Reference to static method in PHP?

前端 未结 8 2431
伪装坚强ぢ
伪装坚强ぢ 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

    This seems to work for me:

    <?php
    
    class Foo{
        static function Calc($x,$y){
            return $x + $y;
        }
    
        public function Test(){
            $z = self::Calc(3,4);
    
            echo("z = ".$z);
        }
    }
    
    $foo = new Foo();
    $foo->Test();
    
    ?>
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题