Itay Grudev
Itay Grudev

Reputation: 7424

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.

Upvotes: 1

Views: 174

Answers (2)

tuxedo25
tuxedo25

Reputation: 4828

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();
   }
}

Upvotes: 4

PeeHaa
PeeHaa

Reputation: 72672

Make the hi() static:

class Class_B{

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

}

Class_B::hi();

Upvotes: 1

Related Questions