php如何查看对象的属性值,如何在PHP中访问包含对象的属性?

我正在编写一些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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值