自从我上次使用object以来已经有一段时间了。我无法弄清楚我做错了什么。我有一个类包含另一个类作为属性。在Item()中实例化ItemDetail()之后,我无法获得描述的值。 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);
?>
答案 0 :(得分: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;
关于可见性