Object Oriented PHP Parent Constructor


Object Oriented PHP Parent Constructor

These two files demonstrate how inheritance works with constructors and the parent constructor. The first file shows how properties are declared within the constructor, while the second file uses the parent constructor(parent::__construct()) to inherit properties. Both files are available for previewing.

Accessing Properties Without Parent Constructor

<?php class Bohemia
{
    protected $_category;
    public $_first_name;
    
    public  function __construct($category, $first_name)
    {
        $this->category = $category;
        $this->first_name = $first_name;
    }
    
    public function get_category()
    {
        return $this->category;
    }
    
    public function get_first_name()
    {
        return $this->first_name;
    }
}

class Blogger extends Bohemia
{
    protected $_email;
    
    public function __construct($category, $first_name, $email)
    {
    $this->first_name = $first_name." and his friend Eugene can be contacted at";
    $this->category = $category;
    $this->email = $email;
    }
    
    public function get_email()
    {
        return $this->email;
    }
}

$blogger = new Blogger('PHP', 'Johnny', 'nerdos@example.com');
echo  $blogger->get_first_name().' the email address "'.$blogger->get_email().'". They love '.$blogger->get_category().'.';
?>

Accessing Properties With Parent Constructor

<?php class Bohemia
{
    protected $_category;
    public $_first_name;
    
    public  function __construct($category, $first_name)
    {
        $this->category = $category;
        $this->first_name = $first_name." and his friend Eugene can be contacted at";
    }
    
    public function get_category()
    {
        return $this->category;
    }
    
    public function get_first_name()
    {
        return $this->first_name;
    }
}

class Blogger extends Bohemia
{
    protected $_email;
    
    public function __construct($category, $first_name, $email)
    {
    parent::__construct($category, $first_name);
    $this->email = $email;
    }
    
    public function get_email()
    {
        return $this->email;
    }
}

$blogger = new Blogger('PHP', 'Johnny', 'nerdos@example.com');
echo  $blogger->get_first_name().' the email address "'.$blogger->get_email().'". They love '.$blogger->get_category().'.';
?>