简体   繁体   中英

abstract member functions fail to access atributes of inheriting class

in php I have this code. I'm trying to get an inherited method to utilize a member variable of its child class.

abstract class HtmlObj{
//abstract protected function jQuery_Activity();
public $hyperlink;
abstract protected function php_Activity();
abstract protected function print_Widget();

function __construct($hyperlink=""){
    if(isset($hyperlink)){
        $this->hyperlink = $hyperlink;
    }
    $this->php_Activity();
    $this->Print_Widget();
}

}

class child extends HtmlObj{
   public $id;
   protected function php_Activity(){return;}
   protected function print_Widget(){
      print $this->id;
   }
   function __construct($id){
     this->id = $id;
   }
}

unfortunately this prints nothing. any insights as to why?

in child class You need to reffer to parent::__construct() by doing something like

abstract class HtmlObj
{
//abstract protected function jQuery_Activity();
    public $hyperlink;

    abstract protected function php_Activity();

    abstract protected function print_Widget();

    function __construct($hyperlink = "")
    {
        if (isset($hyperlink)) {
            $this->hyperlink = $hyperlink;
        }
        $this->php_Activity();
        $this->Print_Widget();
    }
}

class child extends HtmlObj
{
    public $id;

    protected function php_Activity()
    {
        return;
    }

    protected function print_Widget()
    {
        print $this->id;
    }

    function __construct($id)
    {
        $this->id = $id;
        parent::__construct();
   }
}

new child(10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM