0

自从我上次使用对象以来已经有一段时间了。我不知道我做错了什么。我有一个包含另一个类作为属性的类。在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);
?>
4

1 回答 1

2

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

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;

一切都与可见性有关

于 2013-07-03T19:38:16.503 回答