【问题标题】:Create child objects from within the parent?从父对象中创建子对象?
【发布时间】:2017-07-14 18:40:02
【问题描述】:

如何从父对象中创建子对象?

class Section
{
    protected $url;
    function __construct($url)
    {
        $this->url = $url;
    }

    public function createElements()
    {

    } 
}

class ElementA extends Section
{

}

class ElementB extends Section
{

}

每个部分将包含多个元素,但是,部分类的全部目的是创建元素,而不仅仅是存储与该部分相关的数据。

【问题讨论】:

  • 你能给我更多的信息,告诉我你想要什么输出吗?
  • 我正在制作一个 CMS。 section 类用于headerfooterleft column 等部分。变量$url 是服务器上为该部分存储元素的路径。元素类用于元素,例如H2P、'FORM' 等等。目前,这些元素是从一个以$url 为参数的静态函数中生成的。

标签: php class inheritance extends


【解决方案1】:

你可以这样做:

public function createElements()
{
    $this->children[] = new ElementA($this->url);      // use $this->url
    $this->children[] = new ElementB('http://www.google.com'); // or not
}

【讨论】:

  • 我希望该部分中的所有元素只有一个 Section 类的实例,否则它有点违背了拥有 Section 类的目的。我认为这是不可能的,但如果有的话,它肯定会产生更高效的代码。
猜你喜欢
  • 2010-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多