Parent::_construct()

What does “parent::_construct()” do? Does it incorporate all the variables from “_construct” in class1?

class class1 {
     var $a;
     var $b;
     function _construct($a1,$b1){
          $this->a = $a1;
          $this->b = $b1;
     }
}
class class2 extends class1 {
    function _construct(){
    	parent::_construct();
    }
}

Ok, quick OOP lesson :slight_smile:

Firstly your _construct should have 2 underscores before “construct” rather than one, so it should be: __construct.

If class2 extends class1, it means that class2 takes on the variables and functions (in OOP, called: properties and methods). So in your post above, class 2 has $a and $b as variables. If you didn’t create a __construct for class2, it would have taken on the __construct from class1.

So if you override a method from class1 in class2, you can still access it from class1 using “parent::methodName();”.

Here’s an example:


<?php
class Pet{
    protected $Name = '';
    protected $Type = '';
    public function __Construct($Name, $Type)
    {
        $this->Name = $Name;
        $this->Type = $Type;
    }
    public function feed{
        return "You have fed the {$this->Type} {$this->Name}";
    }
}

class Dog extends Pet{
    public function __Construct($Name){
        parent::__Construct($Name, 'Dog');
    }
    public function wagTail(){
        return "{$this->Name} is wagging their tail";
    }
}

$Brian = new Dog('Brian');
echo $Brian->feed();
echo '<br />';
echo $Brian->wagTail();