【发布时间】:2019-11-24 08:00:43
【问题描述】:
显然我错过了一些东西。我有以下代码:
<?php
class module {
protected $registry;
public $controller;
public $model;
public $view;
public $var = 'global';
}
class controller extends module {
public function test_controller() {
echo 'controller test';
echo $this->var;
$this->model->test_model();
$this->view->test_view();
}
}
class model extends module {
public function test_model() {
echo 'model test';
echo $this->var;
}
}
class view extends module {
public function test_view() {
echo 'view test';
echo $this->var;
}
}
$module = new module();
$module->controller = new controller();
$module->model = new model();
$module->view = new view();
echo "\n\n\n" . print_r($module);
$module->controller->test_controller();
最后我得到“在 null 上调用成员函数 test_model()”。我确实理解每次实例化“扩展器”类时都会重新初始化“模块”类的变量。好的,没问题,但在那之后我为“父”类属性分配了所需的“值”(我的意思是 $module->controller = new controller();)。
我不明白如何处理这种行为。我想在我在控制器函数中编写的模块中实现这种类型的引用:$this->model->some_func(), $this->view->some_other()。还将有一个所谓的注册表,其中包含其他类也应该可用于扩展类。
如果这是一个设计问题 - 好吧,请指出我 :)
谢谢。
【问题讨论】:
-
为什么要扩展模块类?
-
控制器的实例有一个空模型和视图。
-
如果你真的想在继承类的不同实例之间共享变量,你可以使用静态属性,你需要以不同的方式引用它们。但这很可能是一种反模式。
-
我扩展了模块类,因为 $registry 中的功能应该对控制器、模型、视图类可用。这是一回事。另一个是我想从控制器(和其他类)中引用模型和其他类,例如 $this->model、$this->api、$this->controller 等。