Access child class static variables from parent class?

后端 未结 2 633
心在旅途
心在旅途 2021-02-05 13:42

I have a base class that I need to call functions on a class that is referenced in the child class.

Easy enough,

class base_class {

    public function          


        
2条回答
  •  走了就别回头了
    2021-02-05 14:26

    Provide a way for the parent to access the child's static member:

    reference()->doSomething();
        }
    }
    
    class extended_class extends base_class{
        protected static $reference;
    
        public function __construct($ref){
            self::$reference = $ref;
        }
    
        protected function reference(){
            return self::$reference;
        }
    }
    
    class ref {
        public function doSomething(){
            echo __METHOD__;
        }
    }
    
    $ref = new ref();
    $ec = new extended_class($ref);
    $ec->doSomethingWithReference();
    
    print_r($ec);
    ?>
    

提交回复
热议问题