我正在编写一些 PHP 代码,其中一个对象(“容器”)保留指向另一个对象(“内容”)的指针。问题是内容需要访问容器的方法或属性。
这是我想做的事情的一个简化示例:
class Container {
function __construct($type, $contents) {
$this->type = $type;
$this->contents = $contents;
}
function display() {
return $this->contents->display();
}
}
class Contents {
function __construct($stuff) {
$this->stuff = $stuff;
}
function display() {
return 'I am ' . $this->stuff . ' in '; // how to access Container here?
}
}
$item = new Container('a can', new Contents('Prince Albert'));
echo $item->display() . "\n";
// Displays: I am Prince Albert in
// Wanted: I am Prince Albert in a can
执行此操作的正确方法是什么?
我尝试了几种有效的方法,但感觉都不对。例如:
重新定义了
Contents::display()
来带一个参数,看起来不太优雅:function display($container) { return 'I am ' . $this->stuff . ' in ' . $container->type; }
在
Contents::display()
中,我调用了debug_backtrace(true)
以找出调用它的原因,然后从回溯信息访问该对象。这感觉很笨拙/危险。
是否有针对此类问题的通用解决方案?
最佳答案
共有两种常见的解决方案。第一个是你已经提到的第一个
class A {
public function doSomething ($outer) { /* code */ }
}
$outer
是您的容器。或者您将内容对象严格绑定(bind)到容器
class A {
private $outer;
public function __construct ($outer) {
$this->outer = $outer;
}
}
关于php - 如何在 PHP 中访问包含对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6062840/