tags:

views:

832

answers:

3

If I have this class:

<?php
class Model
{
    var $db;

    function Model()
    {
        $this->db=new Db_Class();
    }
}
?>

and a second class that extended the parent class:

<?php
class LessonModel extends Model
{

    public function LessonModel()
    {
        //code here
    }

    public function getTitle($id)
    {
       $this->db->setTable('myTable');
       return $this->db->get('title',$id);
    }
}
?>

Is it safe to assume that the $LessonModel->db field would have been instantiated by the parent Model class's constructor, or do I need to run it manually using something like parent::Model();?

A: 

In the given example, you can assume that.

However, if your child class defines a constructor, PHP will not implicitly call it's parent constructor.

In order to do that, call:

parent::__construct();
Mike Hordecki
PHP is so fucking annoying. i miss java
Click Upvote
His child class has defined a constructor using the older naming convention Classname()
Tom Haigh
A: 

There's a cheap way to get around having to call the parent constructor.

Create an empty init() method in the base class. Call $this->init() in the base class constructor.

All sub-classes can implement init() if they want to run code when the class is created.

Matt
+6  A: 

You cannot assume that the parent constructor has been called because you have overridden this in your subclass. You would need to call parent::Model() as you suggest. If you change the class you are inheriting from you would obviously need to change this.

If you are using PHP5 then you can name your constructors __construct(). This has the benefit of letting you easily call a parent constructor by doing parent::__construct() in any derived class without specifying the parent class name. You can then rearrange your classes' inheritance with less hassle and less danger of introducing obscure bugs.

Tom Haigh