【问题标题】:Php recursive object creatingPHP递归对象创建
【发布时间】:2018-03-25 17:28:48
【问题描述】:

当我执行以下操作时:

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

那么,白洞中的宇宙和大宇宙一样,它会像上面那样递归地继续下去。

【问题讨论】:

  • 您定义了 2 个创建彼此新实例的类...当然您会遇到内存错误...
  • 你做错了抽象。它更多的是哲学而不是编程。如果从另一件事创造一件事不是它的本质/本质,为什么你这样描述它们?更好的是,在你的星系中创建 createBlackhole() 方法,在你的 backhole 类中创建 createWhitehole() 等等。在需要时调用。因为星系的存在不是为了创造黑洞,或者黑洞的存在不仅仅是为了创造白洞。所以不要做这样的抽象。如果有一天你会让 Universe 成为你的编译器,那么肯定它也会报错。
  • @marmeladze 是的,我明白了你的想法并尝试了它,它有效。但是,我希望它永远递归地工作。看看 [this link] (orteil.dashnet.org/nested) 并始终扩展第一个元素。我想做类似的事情。

标签: php recursive-datastructures


【解决方案1】:

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

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

【讨论】:

  • 一个白洞不包含原始宇宙,而是一个新的宇宙对象。
  • @DonJoe 好吧,您将无法创建无限深的链,因为您使用的是内存有限的机器。
  • @DonJoe 我检查了你提供的链接,他们使用类似于我的代码的模型,他们只是在你点击时创建新元素
  • 那么我想我的问题的答案是动态创建新元素。将其添加到您的答案中,然后我接受。顺便说一句,在 [此链接] (ibb.co/fEKSs7) 上,您可以看到我从您的解决方案中获得了 *RECURSION* 文本。该 PHP 编译器是否试图保护堆栈溢出或类似的东西?我以前从未见过这种消息,我什至在谷歌上都找不到任何东西......
  • @DonJoe 我更改了我的剪辑以按需生成元素。 *RECURSION* 表示您到达了已经在某处打印的元素。由于您无法打印循环树,解释器只会破坏它
猜你喜欢
  • 2019-09-03
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 2015-04-27
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
  • 2011-06-05
相关资源
最近更新 更多