如何从另一个对象获取对象值


How to get object value from another object

我上次使用对象已经有一段时间了。我不明白我做错了什么。我有一个包含另一个类作为属性的类。在Item()内部实例化ItemDetail()之后,我无法获得description的值。var_dump($item)为$detail的值提供NULL。请帮忙。非常感谢。

<?php
class Item
{
  private $name;
  private $detail;
  function __construct() {
    $this->name = 'some name';
    $this->detail = new ItemDetail();
  }
  function getDetail() {
    return $this->detail;
  }
}
class ItemDetail
{
  private $description;
  function __construct() {
    $this->description = 'some description';
  }
  function getDescription {
    return $this->description;
  }
}
$item = new Item();
echo $item->getDetail()->getDescription();
//var_dump($item);
?>

您需要更改类属性的范围,或者定义一个返回值的方法。示例:

class Item
{
  private $name;
  private $detail;
  function __construct() {
    $this->name = 'some name';
    $this->detail = new ItemDetail();
  }
    public function getDescription() {
        return $this->detail->getDescription();
    }
}
class ItemDetail
{
  private $description;
  function __construct() {
    $this->description = 'some description';
  }
    public function getDescription() { 
        return $this->description;
    }
}
$item = new Item();
echo $item->getDescription();

如果你公开你的房产,你也可以这样得到:

class Item
{
  public $name;
  public $detail;
  public function __construct() {
    $this->name = 'some name';
    $this->detail = new ItemDetail();
  }
}
class ItemDetail
{
  public $description;
  public function __construct() {
    $this->description = 'some description';
  }
}
$item = new Item();
echo $item->detail->description;

这一切都与可见性有关