【发布时间】:2015-09-25 21:08:27
【问题描述】:
我有一个庞大的项目,并且在某些扩展它的点上,我想做一些事情 $this 在子类 Y(继承自 X)中指向 X,当来自 Y 的方法从 @987654326 调用时@ :) 我不能过多地干预类结构,我想在没有任何“助手”、带有“控制器路径”的附加构造函数参数或类似的东西的情况下很好地做到这一点。
所以问题是:当我实例化ControllerGallery 时,它调用构造函数,该构造函数调用父构造函数(来自ControllerResource,它是ControllerGallery 的父构造函数)。但是在父构造函数(ControllerResource)中,变量$this指向ControllerGallery,而不是ControllerResource。
我知道当我实例化类时,只有一个对象被创建(只有“ControllerGallery”,而不是:“ControllerGallery,它是父级ControllerResource”),这就是问题所在。我的问题是:如何达到如下所示的结果?有什么建议吗?
<?php
abstract class Controller {
function getParentController()
{
return null;
}
function getController(){
return $this;
}
}
class ControllerResource extends Controller
{
protected $CONTROLLER_PATH = 'Resource';
protected $scripts;
function __construct(){
$this->addScript($this->CONTROLLER_PATH.DIRECTORY_SEPARATOR.'general_resource_support_script.js');
}
function addScript($name){
$this->scripts[] = $name;
}
function getParentController()
{
return parent::getController();
}
function getScriptPaths(){
return $this->scripts;
}
}
class ControllerProduct extends ControllerResource
{
protected $CONTROLLER_PATH = 'Product';
function __construct(){
parent::__construct();
$this->addScript($this->CONTROLLER_PATH.DIRECTORY_SEPARATOR.'product_support_scripts.js');
}
}
class ControllerGallery extends ControllerResource
{
protected $CONTROLLER_PATH = 'Gallery';
function __construct(){
parent::__construct();
$this->addScript($this->CONTROLLER_PATH.DIRECTORY_SEPARATOR.'gallery_scripts.js');
}
}
$controllerProduct = new ControllerProduct();
$controllerGallery = new ControllerGallery();
echo('<pre>');
print_r($controllerProduct->getScriptPaths());
print_r($controllerGallery->getScriptPaths());
echo('</pre>');
echo('
<pre>
<b>SHOULD BE:</b>
Array
(
[0] => <b>Resource</b>\general_resource_support_script.js
[1] => Product\product_support_scripts.js
)
Array
(
[0] => <b>Resource</b>\general_resource_support_script.js
[1] => Gallery\gallery_scripts.js
)
</pre>
');
?>
我们得到结果:
Array
(
[0] => Product\general_resource_support_script.js
[1] => Product\product_support_scripts.js
)
Array
(
[0] => Gallery\general_resource_support_script.js
[1] => Gallery\gallery_scripts.js
)
但应该是:
Array
(
[0] => Resource\general_resource_support_script.js
[1] => Product\product_support_scripts.js
)
Array
(
[0] => Resource\general_resource_support_script.js
[1] => Gallery\gallery_scripts.js
)
【问题讨论】:
标签: php oop object inheritance parent