Faking Late Static Binding before php 5.3

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

    Often, late static binding is needed when a child calls back a method of the parent who, in turn, calls an abstract static method of the child. I was in such a postition, and could not use static:: as my PHP was not version 5.3 (or later). The following accomplished late static binding by way of debug_backtrace().

    abstract class ParentClass
    {
        static function parent_method()
        {
            $child_class_str = self::get_child_class();
            eval("\$r = ".$child_class_str."::abstract_static();");
            return $r;
        }// CHILD MUST OVERRIDE TO PUT ITSELF INTO TRACE
    
        protected abstract static function abstract_static(); // THIS NEEDS LATE STATIC BINDING
    
        private static function get_child_class()
        {
            $backtrace = debug_backtrace();
            $num = count($backtrace);
            for($i = 0; $i < $num; $i++)
            {
                 if($backtrace[$i]["class"] !== __CLASS__)
                      return $backtrace[$i]["class"];
            }
            return null;
        }
    }
    
    class ChildClass extends ParentClass
    {
        static function parent_method(){ return parent::parent_method(); }
    
        protected static function abstract_static()
        {
            return __METHOD__."()";
        }// From ParentClass
    }
    
    print "The call was: ". ChildClass::parent_method();
    

提交回复
热议问题