【发布时间】:2016-11-12 12:30:23
【问题描述】:
我有一个非常简单的 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']).'"/>';
}
}
所以我希望子类继承父类的属性和方法。然后,当我获得对子类的引用时,它应该能够使用 img_cache 对象。但我在这里遇到一个致命错误:Call to a member function thumb() on a non-object。
我哪里做错了?
【问题讨论】:
-
您需要扩展子类以使其继承父类的属性。 php.net/manual/en/keyword.extends.php
-
class ChildView extends View -
您对 OOP 的理解有问题。不要在 View 类中创建对象 ChildView。相反,扩展 View 并在您的主控制器中调用
new ChildView();。 -
@MP_Webby 请避免编辑您的原始问题。这样以后的读者就不会知道原始代码和答案有什么不同了。
-
@PEMapModder,是的,我明白这一点。这是一个错字,只是让我的问题更清楚。问题的主题没有改变。
标签: php oop inheritance