0

Can I extend the constructor of the sueprtype? documentation doesnt say anything about extending functions.

I want to create a class which connects to a database when the subtypes are initialized but I don't want to write a connection code for each subtype. So I'd like to do it in the constructor of the supertype but I also want subtypes to have constructors.

Uğur Gümüşhan
  • 2,455
  • 4
  • 34
  • 62
  • 2
    see [this](http://stackoverflow.com/questions/151969/php-self-vs-this.) and [this](http://stackoverflow.com/questions/1136184/using-this-self-parent-for-code-readability) – xkeshav Nov 17 '11 at 05:35

4 Answers4

1

Methods don't get "extended" per se; classes get extended. The methods of those classes still exist, and can be invoked if they are scoped appropriately.

To more directly answer your question, you can call parent::__construct() to invoke the __construct() method of a superclass. See the PHP documentation on constructors and destructors for more information.

Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
1

From php.net

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

http://www.php.net/manual/en/language.oop5.decon.php

So what you do is connect to the database in the superclass constructor. Then create your subclass constructor and call parent::__construct()

But, it would probably be better to explicitly connect. In the base class call $this->connect(), which would be defined in the parent class.

Galen
  • 29,976
  • 9
  • 71
  • 89
1

Just as you can use parent::methodName() to call the parents version of a function, so you can call self::methodName() to call the current classes implementation of a method.

This links may help u

http://www.php.net/manual/en/language.oop5.basic.php#102275

Community
  • 1
  • 1
xkeshav
  • 53,360
  • 44
  • 177
  • 245
1

Yes, you can override the constructor just like any other method in a class:

<?php
class DbSuper {
    function __construct() {
        echo "db connection using super class<br/>";
    }
}

class DbSub extends DbSuper {
    function __construct() {
        echo "db connection using sub class<br/>";
    }
}

class DbSubNoConstr extends DbSuper {

}

class DbSubBothConstr extends DbSuper {
    function __construct() {
        echo "execute subclass code<br/>";
        parent::__construct();
    }

}

new DbSub(); //prints db connection using sub class
new DbSubNoConstr(); // prints db connection using super class
new DbSubBothConstr(); // prints execute subclass code db connection using super class
?>
Sheldon Fernandes
  • 1,299
  • 1
  • 11
  • 18