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

标签 php oop

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

相关文章:

PHP 生成随机数作为数组显示(通过单击选择框)

php - Mysql分层数据按路径查找

php - App\Http\Controllers\缺少参数 1

oop - 我可以在这里应用 Liskov 替换原则吗

c++ - 为什么以及何时通过指针在 C++ 中传递类类型?

php - PHP中 explode 两次的更好方法

php - 检查禁止功能

c++ - STL 如何使用非线性数据结构实现反向迭代器取消引用?

c# - 抽象类和只读属性

c++ - 如何避免在基类初始值设定项中调用默认构造函数?