Свойство объекта PHP сам по себе является другим объектом другого класса - PullRequest
0 голосов
/ 29 мая 2020

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

1 Ответ

0 голосов
/ 29 мая 2020

Сделайте так:

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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...