php - PHP 对象本身的属性是另一个类的另一个对象
问题描述
我很确定我们可以使用不同类的对象来存储对对象属性的引用。但我被这段代码困住了。
两者的__construct()
功能metro
和为这些对象town
分配值$name
和$pop
。但是我需要类的__construct()
功能city
来创建类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;
?>
解决方案
做这个:
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);
}
$this->derived_city = $derived_city;
}
}
$city1 = new city("Bombay",100);
print_r($city1->derived_city);
echo $city1->derived_city->pop;
推荐阅读
- json - 在 jsonapi 中包含具有相同 ID 和类型的多个关系的方法
- android - Ionic - APK Build 总是生成具有旧值的旧 apk
- java - OpenStack4j - 有没有一种方法可以在存储对象中获取对象的临时 url?
- svn - diff 两个源代码目录过滤掉 CVS/SVN 关键字
- scala - Akka Actors 中消息的传递顺序
- python - 改进 ssd 的 numpy 负载性能测试
- outlook - 如何使用 UI 路径或不使用 UI 路径获取 Outlook 通讯录的转储/导出?
- flutter - 按下浮动按钮时,我的应用程序在 launch_url 上引发接受错误
- python - AttributeError:模块 'skopt' 没有属性 'plots' 错误消息
- javascript - Discord.js Collection() 比 Objects 或 Maps 更好吗?