Search code examples
phpclassmethodsextendpublic-method

Fatal allowed memory size exceeded when using class extend


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?


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?