Reference to static method in PHP?

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

    In php 5.2, you can use a variable as the method name in a static call, but to use a variable as the class name, you'll have to use callbacks as described by BaileyP.

    However, from php 5.3, you can use a variable as the class name in a static call. So:

    class Bar
    {
        public static function foo2($a,$b) { return $a/$b; }
    
        public function UseReferences()
        {
            $method = 'foo2';
            print Bar::$method(6,2); // works in php 5.2.6
    
            $class = 'Bar';
            print $class::$method(6,2); // works in php 5.3
         }
    }
    
    $b = new Bar;
    $b->UseReferences();
    ?>
    

提交回复
热议问题