Search code examples
phpclassparentextend

Loading Class Extensions from Inside the Parent class PHP


I am trying to load an extension of a php class by itself. I don't understand why it isn't loaded. Is it possible to load class extensions from themselves?

Here is a code example of what exactly I mean.

class Class_B{
     public function hi(){
          echo('Hello world!');
     }    
}

class Class_D extends parent{
     public function Class_D(){
          //--> Here is the problematic line
          $this->class_b->hi();
     }    
}

class parent{
     public $class_b;

     public function __construct(){
          $this->class_b = new Class_B;
          new Class_D();
     }
}

This code comes with this error.

Call to a member function hi() on a non-object in /path/to/your/application/test.php on line 59

I need to call the Class_B::hi() function using the same syntax. I read a lot, but I didn't found what I need. In CodeIgniter the different libraries are called like that. I wanted to achieve something similar in my program. Thanks.


Solution

  • You definitely don't want to call new Class_D() from within the parent constructor.

    I think what you're trying to do is:

    class parent {
         protected $b;
    
         public function __construct() {
              $this->b = new Class_B();
         }
    }
    
    class Class_D extends parent {
        function __construct() {
           parent::__construct();
    
           $this->b->hi();
       }
    }