Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 是否从父对象中创建子对象?_Php_Class_Inheritance_Extends - Fatal编程技术网

Php 是否从父对象中创建子对象?

Php 是否从父对象中创建子对象?,php,class,inheritance,extends,Php,Class,Inheritance,Extends,如何从父对象中创建子对象 class Section { protected $url; function __construct($url) { $this->url = $url; } public function createElements() { } } class ElementA extends Section { } class ElementB extends Section { }

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

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

    public function createElements()
    {

    } 
}

class ElementA extends Section
{

}

class ElementB extends Section
{

}

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

您可以这样做:

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

你能给我更多的信息,告诉我你想要什么输出吗?我正在做一个CMS。节类用于节,例如,
页眉
页脚
左列
等。变量
$url
是服务器上存储节元素的路径。元素类用于元素,例如
H2
P
、“FORM”和许多其他元素。目前,这些元素是在一个静态函数中生成的,该函数将
$url
作为参数。我希望只有一个Section类的实例用于Section中的所有元素,否则它就有点违背了创建Section类的目的。我甚至不认为这是可能的,但如果有,肯定会产生更高效的代码。