【发布时间】:2020-05-29 18:08:28
【问题描述】:
我很确定我们可以使用不同类的对象来存储对对象属性的引用。
但我被这段代码困住了。 metro 和 town 的 __construct() 函数为这些对象的 $name 和 $pop 分配值。但是我需要city 类的__construct() 函数来创建metro 类或town 类的新对象,具体取决于$pop 类city 的对象的值
<?php
class metro
{
public $name;
public $pop;
function __construct($name,$pop)
{
$this->name = $name;
$this->pop = $pop;
}
}
class town
{
public $name;
public $pop;
function __construct($name,$pop)
{
$this->name = $name;
$this->pop = $pop;
}
}
class city
{
public $name;
public $pop;
public $derived_city;
function __construct($name,$pop)
{
$this->name = $name;
$this->pop = $pop;
if ($this->pop >= 50)
{
$derived_city = new metro($this->name,$this->pop);
}
else
{
$derived_city = new town($this->name,$this->pop);
}
}
}
$city1 = new city("Bombay",100);
echo $city1->derived_city->pop;
?>
【问题讨论】:
-
你需要分配
$this->derived_city而不是$derived_city。 -
非常感谢您的澄清。我弄错了..