PHP如何区分继承链中的$ this指针?
Please look at the following code snipped
请查看以下代码剪切
class A
{
function __get($name)
{
if ($name == 'service') {
return new Proxy($this);
}
}
function render()
{
echo 'Rendering A class : ' . $this->service->get('title');
}
protected function resourceFile()
{
return 'A.res';
}
}
class B extends A
{
protected function resourceFile()
{
return 'B.res';
}
function render()
{
parent::render();
echo 'Rendering B class : ' . $this->service->get('title');
}
}
class Proxy
{
private $mSite = null;
public function __construct($site)
{
$this->mSite = $site;
}
public function get($key)
{
// problem here
}
}
// in the main script
$obj = new B();
$obj->render();
Question is: in method 'get' of class 'Proxy', how I extract the corresponding resource file name (resourceFile returns the name) by using only $mSite (object pointer)?
问题是:在类'Proxy'的方法'get'中,如何通过仅使用$ mSite(对象指针)提取相应的资源文件名(resourceFile返回名称)?
1 个解决方案
#1
What about:
public function get($key)
{
$file = $this->mSite->resourceFile();
}
But this requires A::resourceFile()
to be public
otherwise you cannot access the method from outside the object scope - that's what access modifiers have been designed for.
但是这需要A :: resourceFile()是公共的,否则你无法从对象范围之外访问该方法 - 这就是为其设计的访问修饰符。
EDIT:
OK - now I think I do understand, what you want to achieve. The following example should demonstrate the desired behavior:
好的 - 现在我想我明白了,你想要实现的目标。以下示例应演示所需的行为:
class A
{
private function _method()
{
return 'A';
}
public function render()
{
echo $this->_method();
}
}
class B extends A
{
private function _method()
{
return 'B';
}
public function render()
{
parent::render();
echo $this->_method();
}
}
$b = new B();
$b->render(); // outputs AB
But if you ask me - I think you should think about your design as the solution seems somewhat hacky and hard to understand for someone looking at the code.
但是如果你问我 - 我认为你应该考虑你的设计,因为解决方案似乎有点hacky并且很难理解看到代码的人。
更多相关文章
- php对象的实现
- PHP:将simpleXML对象转换为二维数组
- 如何对继承对象进行单元测试?
- PHP中类和对象的相关函数
- 【PHP面向对象(OOP)编程入门教程】15.static和const关键字的使用
- PHP XAMPP配置PHP环境和Apache80端口被占用解决方案
- PHP面向对象笔记 —— 113 封装概念
- PHP的语言特性-面向对象和C++/java/python的相似之处
- php面向对象之抽象类和接口理解