繁体   English   中英

PHP递归对象创建

[英]Php recursive object creating

当我执行以下操作时:

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

然后,白洞中的宇宙与大宇宙相同,它将以上述方式递归继续。

在您的代码中,创建A,创建B,创建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];

我们根据需要创建元素,这可能会提供足够好的无限幻觉

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM