DonJoe
DonJoe

Reputation: 1763

Php recursive object creating

When I do the following:

class AA {
    public $a = '';

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

class BB {
    public $b = '';

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

I get Fatal error: Allowed memory size of X bytes exhausted.

Is it even possible to achieve what I am trying to do above?

What am I trying to accomplish:

Let's say I have objects:

Universe:
  Galaxy
  Galaxy
  Galaxy

Galaxy:
  Blackhole
  Star
  Star
  Star
  Star

Blackhole:
  Whitehole

Whitehole:
  Universe

Then, Universe in white hole is same as big universe and it would continue as above, recursively.

Upvotes: 0

Views: 279

Answers (1)

mleko
mleko

Reputation: 12233

In your code you create A, which creates B, which creates another A, which creates another B, and so on. So yes in the end you will run out of memory.

I guess what you trying to do is

<?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];

We create elements as they are requested, which might provide good enough illusion of infinity

Upvotes: 3

Related Questions