Question

When I use a lot of class extends, I get this error:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65488 bytes) in C:\Web\private\bootstrap.php on line 5 (I made sure this is actually the line for the code below. My original code said line 22.)

This is my code (massively abridged, but still creates the error. My original has this->this 6 levels deep!).

class test { // Root class.
    public $system;
    function __construct() {
        $this->system = new system();
    }
}
class system extends test { // System classes and methods.
    public function demo($string = 0){echo $string;}
}
$test = new test();
$test->system->demo("hello");

This should output a mere hello but unfortunately it throws the error instead. What is causing this problem?

Was it helpful?

Solution

Recursion

When you instantiate system, you are extending test which is calling the __construct() method, which is in turn creating a new system object, which extends test and calls __construct(), etc, etc.

Why are you creating a new system object in your test class if system extends test?

OTHER TIPS

You code is causing an infinite loop of recursion.

When you create a new Test, it creates a new System, which calls Test's constructor (since it is inheriting it), which creates a new System ... repeat.

If you removed the inhertience from system, then it will work fine.

class system { // System classes and methods.
    public function demo($string = 0){echo $string;}
}

You are creating an infinite loop.

When you try to instantiate new test(). Your constructor creates a new system object (which itself is a test object, you it would then instantiate another system object and on and on until you run out of memory.

If you don't need the system object to instantiate a new system object you should override the constructor (with an empty function even).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top