首页 > 解决方案 > 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;
?>

标签: phpclassobject

解决方案


做这个:

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;

推荐阅读