OO PHP - 子类不继承父方法和属性

MP_*_*bby 0 php oop inheritance

我有一个非常简单的OO类结构,无法理解为什么子类没有继承父类的属性和方法.

这是我设置的基本示例:

//Main class:
class Main{

    //construct
    public function Main(){
        //get data from model
        $data = $model->getData();

        //Get the view
        $view = new View();

        //Init view
        $view->init( $data );

        //Get html
        $view->getHTML();
    }

}


//Parent View class
class View{

    public $data, $img_cache; 

    public function init( $data ){       
        $this->data = $data;
        $this->img_cache = new ImageCache();
    }

    public function getHTML(){

        //At this point all data is intact (data, img_cache)

        $view = new ChildView();

        //After getting reference to child class all data is null
        //I expected it to return a reference to the child class and be able to 
        //call the parent methods and properties using this object. 

        return $view->html();
    }

}


//Child View Class
class ChildView{

    public function html(){

        //I get a fatal error here: calling img_cache on a non-object.
        //But it should have inherited this from the parent class surely?

        return '<img src="'.$this->img_cache->thumb($this->data['img-src']).'"/>';       
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我希望子类继承父类的属性和方法.然后,当我获得对子类的引用时,它应该能够使用该img_cache对象.但我在这里得到一个致命的错误:Call to a member function thumb() on a non-object.

我哪里出错了?

Dom*_*Dom 5

您需要使用扩展基类来指定继承http://php.net/manual/en/keyword.extends.php

试试这个为你的孩子上课

//Child View Class
class ChildView extends View{

    public function html(){

        //I get a fatal error here: calling img_cache on a non-object.
        //But it should have inherited this from the parent class surely?

        return '<img src="'.$this->img_cache->thumb($this->data['img-src']).'"/>';       
    }
}
Run Code Online (Sandbox Code Playgroud)

同样正如@ferdynator所说,你是实例化父,而不是子,所以你的Main类也需要更改为实例化ChildView,而不是父类View

//Main class:
class Main{

    //construct
    public function Main(){
        //get data from model
        $data = $model->getData();

        //Get the view
        $view = new ChildView();

        //Init view
        $view->init( $data );

        //Get html
        $view->getHTML();
    }

}
Run Code Online (Sandbox Code Playgroud)