Marc Rasmussen
Marc Rasmussen

Reputation: 20565

Constructing objects that extends a super class that has its own constructor

I was unsure what to call this so feel free to edit the title.

I am trying to create my own API. within this API there are certain objects these objects all extends the super class ApiObject:

    class ApiObject {
    protected $sqltemplate;
    public function __construct($db){
        $this->sqltemplate = new sqlTemplates($db);
    }

    protected function getTemplate(){
        return $this->sqltemplate;
    }

}

Now an example of the objects that extends this class is:

class Group extends ApiObject {


public function __construct(){

}

public function findByUserId(){

}

public function findByTeam(){

}

Now my question is as follow:

When i construct a type of the Group object is the ApiObject's contructor always called? and if so how does it pass the parameter $db to the constructor?

Upvotes: 0

Views: 45

Answers (1)

akirk
akirk

Reputation: 6857

You have all the code, why don't you just try it?

<?php
class ApiObject {
    public function __construct($db){
        echo __METHOD__, "($db)\n";
    }
}

class Group extends ApiObject {
    public function __construct(){
            echo __METHOD__, "\n";
    }
}

new Group;

outputs

Group::__construct

This shows that the constructor of the parent object is not called automatically. You have to do this via parent::__construct($db) and add the $db parameter to the second constructor.

<?php
class ApiObject {
    public function __construct($db){
        echo __METHOD__, "($db)\n";
    }
}

class Group extends ApiObject {
    public function __construct($db){
            echo __METHOD__, "\n";
            parent::__construct($db);
    }
}

new Group("db");

outputs

Group::__construct
ApiObject::__construct(db)

For a better understanding: Group::__construct overwrites the parent constructor, that's the reason you have to call it manually. If you don't specify a constructor, the parent constructor is called automatically. Example:

<?php
class ApiObject {
    public function __construct($db){
        echo __METHOD__, "($db)\n";
    }
}

class Group extends ApiObject {
}

new Group("db");

outputs

ApiObject::__construct(db)

Upvotes: 1

Related Questions