[英]Accessing an extended class method from a sibling extended class (PHP OOP)
首先,我对OOP以及MVC都比较陌生,因此如果我使用的术语不正确或感到困惑,我深表歉意(因为我是,哈哈)
我将尽可能从基本开始,如果您需要更多信息,请告诉我。
我正在使用Panique的MVC(版本巨大) https://github.com/panique/huge
所以这里什么都没有!
我有一个像这样设置的基本控制器类...
调节器
<?php
class Controller {
public $View;
function __construct() {
$this->View = new View();
}
}
?>
使用这样的一些扩展控制器类(我将在这里显示两个)
的IndexController
class IndexController extends Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->View->render('index');
}
}
?>
ProfileController可
class ProfileController extends Controller {
public function __construct() {
parent::__construct();
}
public function profile() {
$this->View->render('profile');
}
}
?>
我的问题是,当两个扩展类方法具有相同的父类时,在另一个扩展类方法中使用扩展类方法(如果有可能)。 就像是...
<?php
class ProfileController extends Controller {
public function __construct() {
parent::__construct();
}
public function profile() {
$this->IndexController->index(); //Here I would like to use the method from the IndexController
}
}
?>
我已经尝试了很多尝试来完成这项工作,但是我认为我对OOP的了解不足阻碍了我的工作。 除了少数情况,我尝试的所有操作似乎都抛出了...错误。
Fatal error: Class 'IndexController' not found in blah/blah/ProfileController.php
我认为,如果我能够学习以正确的方式针对扩展类的话,我可以管理其余的……希望;)
没有简单或优雅的方法可以做到这一点。 您将需要实例化该类中需要借用代码的另一个类,这可能会在您的应用程序中引起许多副作用。
可能有其他方法可以做到这一点,这也取决于框架的可能性/局限性,但是从PHP中的OOP角度考虑,忽略其他因素,最好的方法是在一种方法上实现共享代码控制器类:
<?php
class Controller {
public $View;
function __construct() {
$this->View = new View();
}
protected function myCustomCode() {
...
}
}
?>
然后通常在后代上调用它:
<?php
class IndexController extends Controller {
public function __construct() {
parent::__construct();
}
public static function index() {
$this->myCustomCode();
$this->View->render('index');
}
}
?>
<?php
class ProfileController extends Controller {
public function __construct() {
parent::__construct();
}
public function profile() {
$this->myCustomCode();
...whatever...
}
}
?>
我看不出有更好的方法。 此外,这是OOP的自然方式,其中常见的东西出现在类层次结构上(祖先),而不是横向出现或下降(后代)。 这有助于使代码保持逻辑性并易于维护。
包括类IndexController的文件:
require_once('IndexController.php');
$this->controller = new IndexController();
然后调用方法
$this->IndexController->index();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.