Faking Late Static Binding before php 5.3

前端 未结 6 1610
天命终不由人
天命终不由人 2021-01-04 13:04

I need an inherited static function \"call\" to call another static function \"inner\" that has been overridden. I could do this with late static binding, but my host does

6条回答
  •  清酒与你
    2021-01-04 13:38

    Here's a quick example.

    inner();
       }
    
       static function inner(){
          return "Class A";
       }
    
       static function init($class){
          return new $class();
       }   
    }
    
    class ClassB extends ClassA{
       static function inner(){
          return "Class B";
       }
    }
    
    echo "

    Class A = " . ClassA::init("ClassA")->call(); echo "

    Class B = " . ClassB::init("ClassB")->call(); ?>

    If you don't like passing in the class name you could add a static init function to the child class and explicitly pass it there as well. This would allow you to do something like: ClassA::init()->call() and ClassB::init()->call() but would have some minor code duplication.

提交回复
热议问题