我正在编写一些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)来查找调用它的内容,然后从backtrace信息中访问该对象.这感觉很危险/危险.
这种问题有一个共同的解决方案吗?
解决方法:
试试这个:
class Container
{
protected $type;
protected $contents;
function __construct($type, Contents $contents)
{
$this->type = $type;
$this->contents = $contents;
$contents->setContainer($this);
}
function display()
{
return $this->contents->display();
}
public function getType()
{
return $this->type;
}
}
class Contents
{
/** @var Container */
protected $container;
function __construct($stuff)
{
$this->stuff = $stuff;
}
public function setContainer(Container $container)
{
$this->container = $container;
}
function display()
{
return 'I am '.$this->stuff.' in '.$this->container->getType(); // 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
标签:php,oop
来源: https://codeday.me/bug/20190531/1187358.html