gpt4 book ai didi

php - 如何在 PHP 中访问包含对象的属性?

转载 作者:可可西里 更新时间:2023-10-31 22:47:55 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com