php child class constructor called with parent object as parameter

I am not that good yet on php syntax, so here is my question:

I have a class Foo.

Read More

Class Bar extends Foo.

I want to make a constructor for Bar that is called with an instance of class Foo as parameter, and make an instance of Bar that looks just like the instance of class Foo.

It seems I have to do this because Foo is a class in a WordPress plugin. I am writing a plugin to go on top of the original plugin, and in the filter I can add to, I get the Foo object.

I am open to doing this in the “right” way, if I can just learn the “right” way to do it.

so:

class Foo {      // in the original plugin
   public function __construct() {
       <do some stuff>
   }
}

class Bar extends Foo {     // in my plugin to extend the original plugin
   public function __construct($myFooObject) {
      <I want: $this = $myFooObject; but it doesnt work>
      <do some stuff special to Bar>
   }
}

Related posts

Leave a Reply

2 comments

  1. Well. You are already inheriting the features and members of the Foo class. What you just have missed to do here, is to call the parent class’s constructor (Foo’s constructor).

    Add the following line to your Bar’s __construct():

    parent::__constrcut();
    

    Bar now looks like this:

    class Bar extends Foo {     // in my plugin to extend the original plugin
       public function __construct($myFooObject) {
          parent::__construct(); // we've added this line to call the parent constructor
          <do some stuff special to Bar>
       }
    }
    

    Calling parent constructor in the child class constructor keeps the integrity of your objects and also allows the child class to have a dynamic access to its parent.

  2. <?php
    
    class Bar extends Foo { // in my plugin to extend the original plugin
       public function __construct($myFooObject) {
         foreach (get_object_vars($myFooObject) as $key=>$value){
            $this->$key = $value;
         }
    
         // <I want: $this = $myFooObject; but it doesnt work>
         // <do some stuff special to Bar>
       }
    }
    

    This will not only instantiate with Foo properties, but copy $myFooObject Properties on creation.