Faking Late Static Binding before php 5.3

前端 未结 6 1648
天命终不由人
天命终不由人 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:48

    You can use object instances rather than classes. If you want a global symbol, you can use a global variable. Since they are rather unwieldy in PHP, one trick is to wrap it in a function. Eg.:

    class ClassA {
      function call() {
        return $this->inner();
      }
      function inner() {
        return "Class A";
      }   
    }
    function ClassA() {
      static $instance;
      return $instance ? $instance : new ClassA();
    }
    
    class ClassB extends ClassA {
      function inner() {
        return "Class B";
      }
    }
    function ClassB() {
      static $instance;
      return $instance ? $instance : new ClassB();
    }
    
    echo "

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

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

    But a better idea might be to avoid global symbols altogether; The reason why it works well in Ruby/Rails, is that Ruby doesn't really have static state in the same way that PHP has. A class can be rebound and added to at runtime, which allows for easy extension of the framework. In PHP, classes are always final, so referring to them in application code, is a very strong degree of coupling.

提交回复
热议问题