Я почти уверен, что мы можем сохранить ссылку на свойство объекта с помощью объекта другого класса. Но я застрял с этим кодом.
Функции __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;
?>