【问题标题】:Property of a PHP Object itself is another Object of another classPHP 对象本身的属性是另一个类的另一个对象
【发布时间】:2020-05-29 18:08:28
【问题描述】:

我很确定我们可以使用不同类的对象来存储对对象属性的引用。 但我被这段代码困住了。
metrotown__construct() 函数为这些对象的 $name$pop 分配值。但是我需要city 类的__construct() 函数来创建metro 类或town 类的新对象,具体取决于$popcity 的对象的值

<?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-&gt;derived_city而不是$derived_city
  • 非常感谢您的澄清。我弄错了..

标签: php class object


【解决方案1】:

这样做:

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;

【讨论】:

  • 非常感谢您的澄清。我弄错了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
相关资源
最近更新 更多