Php递归对象创建

时间:2018-03-25 17:28:48

标签: php recursive-datastructures

当我执行以下操作时:

class AA {
    public $a = '';

    function __construct() {
        $this->a = new BB();
    }
}

class BB {
    public $b = '';

    function __construct() {
        $this->b = new AA();
    }
}

我得到Fatal error: Allowed memory size of X bytes exhausted

甚至可以实现我上面尝试做的事情吗?

我想要完成的任务:

我们说我有对象:

Universe:
  Galaxy
  Galaxy
  Galaxy

Galaxy:
  Blackhole
  Star
  Star
  Star
  Star

Blackhole:
  Whitehole

Whitehole:
  Universe

然后,白洞中的宇宙与大宇宙一样,并且会以递归方式继续如上所述。

1 个答案:

答案 0 :(得分:3)

在你的代码中你创建了A,它创建了B,它创建了另一个A,它创建了另一个B,依此类推。所以是的,你最终会耗尽内存。

我猜你要做的是

<?php

abstract class Element {
    private $elements;
    abstract protected function createElements();
    public function getElements() {
        if(null === $this->elements) {
            $this->elements = $this->createElements();
        }
        return $this->elements;
    }
}

class Whitehole extends Element{
    protected function createElements() {
        return [new Universe()];
    }
}
class Blackhole extends Element{
    protected function createElements() {
        return [new Whitehole()];
    }
}
class Galaxy extends Element{
    protected function createElements() {
        return [new Blackhole(), new Star(), new Star(), new Star(), new Star()];
    }
}
class Universe extends Element{
    protected function createElements() {
        return [new Galaxy(), new Galaxy(), new Galaxy()];
    }
}
class Star extends Element{
    protected function createElements() {
        return [];
    }
}

$universe = new Universe();
$universe->getElements()[0]->getElements()[0];

我们根据要求创建元素,这可能提供足够好的错觉的无穷大