PHP Inheritance Question - php

If I have the following class:
class foo {
function __construct() {
// Some code
}
}
And then use inheritance to create:
class bar extends foo {
// Some code
}
When I instantiate class 'bar', will it automatically execute the __construct method from 'foo' or do I need to do something else to get that method to execute?

From the manual:
Note: Parent constructors are not
called implicitly if the child class
defines a constructor.
While the documentation doesn't state it explicitly, the inverse of this sentence is also true, i.e., parent constructors are called implicitly if the child class does not define a constructor. Therefore, in your example, instantiating bar would call foo::__construct automatically.

it works, the constructer from the parent class will be inherited.
if you define a new constructor in the instaciated class, it will override the constructor function of the parent class. if you still want to execute the parent constructer you should include
parent::__construct();
in the constructer of thje isntanciated class

The __construct will carry over, yes.
The issue comes when you want to add something to that function, which is when the parent class comes in handy.
class bar extends foo {
$this->doSomethingElse();
parent::__construct();
}

Of course when you extend a class, the subclass inherits all of the public and protected methods from the parent class.

Related

PHP OOP class construct inheritance

I am trying to understand one PHP OOP concept, lets say i have two classes A and B. B extends A there fore A is Base/Parent class. If class A has a __construct class B will automatically inherit it...?
Example:
class Car
{
public $model;
public $price;
public function __construct()
{
$this->model = 'BMW';
$this->price = '29,00,00';
}
}
class Engine extends Car
{
parent::__construct();
}
By parent::__construct(); class Engine will execute Car __construct(); automatically?
But I always though if I inherit from parent class the __construct will be executed automatically anyway why would I add this parent::__construct()?
When one class extends another, it inherits all its methods. Yes, that includes the constructor. You can simply do class Engine extends Car {}, and Engine will have a constructor and all other properties and methods defined in Car (unless they're private, which we'll ignore here).
If you define a method of the same name as already exists in Car in Engine, you're overriding that method implementation. That's exactly what it sounds like: instead of Car's implementation, Engine's method is called.
why would I add this parent::__construct()?
If you're overriding a method, yet you also want to call the parent's implementation. E.g.:
class Engine extends Car {
public function __construct() {
parent::__construct();
echo 'Something extra';
}
}
Overriding a constructor in a child class is exactly that, overriding... you're setting a new constructor for the child to replace the parent constructor because you want it to do something different, and generally you won't want it to call the parent constructor as well..... that's why you need to explicitly call the parent constructor from the child constructor if you want them both to be executed.
If you don't create a child constructor, then you're not overriding the parent constructor, so the parent constructor will then be executed

Are parent constructors called if a child class does NOT define a constructor?

In the PHP Constructors and Destructors documentation it states
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.
But what if the child class does not call a constructor, will the parent constructor still be called? Or should we create a constructor that calls the parent constructor anyway?
IE:
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
}
}
Maybe this was sort of obvious but did some looking around, and a direct answer to this question surprisingly wasn't very easy to find so here it is:
If the child class does NOT define a constructor then the parent constructor will be called.
In the example below $obj will still call the constructor from BaseClass because SubClass never called a constructor.
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}
class SubClass extends BaseClass {
//I do not have a constructor :(
}
$obj = new SubClass();
Take into account a constructor is a method that can be overridden as any other method. If the parent class has a constructor, all its children classes will inherit that constructor. If a child overrides the constructor, this will be used when creating new objects and parent's constructor is not called implicitly. If the child does not override the constructor, the parent's constructor will be used. This concept applies to multiple inheritance.

If I don't define a constructor for a subclass, can I use the constructor of the superclass directly?

Are constructors inherited or do they belong to the class they are defined in? I only have seen examples with constructors of subclasses which call superclass' constructors. This is my current code, which can give some hint about what's going on. (I will change the code according to your replies. If I can use the constructor of the superclass, I won't define a constructor for each subclass and call superclass' constructor from each.
abstract class view
{
public $vieverid;
function __construct($viewerid) {
$this->viewer = $viewerid;
}
}
class viewactor extends view{
function __construct($viewerid) {
$this->viewerid = $viewerid;
}
According to my understanding, PHP doesn't auto-call parent's constructor if child constructor is defined. Otherwise it does.
In child constructor you have to call parent's constructor manually.
abstract class view
{
public $vieverid;
function __construct($viewerid) {
$this->viewer = $viewerid;
}
}
class viewactor extends view{
function __construct($viewerid) {
parent::__construct($viewerid); // manual call
// do your stuff here...
$this->viewerid = $viewerid;
}
parent::__construct(params); use for calling superclass constructor
PHP4
PHP doesn't call constructors of the base class automatically from a
constructor of a derived class. It is your responsibility to propagate
the call to constructors upstream where appropriate.
PHP5
PHP doesn't call constructors of the base class if new constructor defined.
If you define a constructor for derived class
It is your responsibility to propagate
the call to constructors upstream where appropriate.
parent::__construct(params)
Constructors
abstract class view
{
public $vieverid;
function __construct($viewerid) {
$this->vieverid= $viewerid;
}
}
class viewactor extends view{
function __construct($viewerid) {
parent::__construct($viewerid);
// Extra code if you want
}
}
class viewactor_construct extends view{
// Works in PHP5
}
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.
See here

Inheritance problem: calling parent construct function in subclass

I have a class named Display which extends class Layout, which extends class DOMDocument. I get: Fatal error: Call to a member function loadHTMLFile() on a non-object. Code as follows:
In index.php :
$dom = new Display();
$dom->displayData();
In Display.php :
class Display extends Layout {
public function displayData(){
$dom = parent::__construct();
$dom->loadHTMLfile("afile.html");
echo $dom->saveHTML();
}
}
My question is: When I call parent::__construct() , isn't this the same as using "new DOMDocument", since the Display class extends Layout and DOMDocument?Thanks
__construct() is a magic method that is called when you instantiate the object.
Calling it is not the same as using the new operator.
In my experience, I have only ever used parent::__construct() inside of the __construct() of a subclass when I need the parent's constructor called.
If you have the loadHTMLfile function in your parent class, the subclass will inherit it. So you should be able to do:
class Display extends Layout {
public function displayData(){
$this->loadHTMLfile("afile.html");
echo $this->saveHTML();
}
}
It is not the same because constructor in php doesn't return anything
You typically call the parent's constructor inside the subclass's constructor. You're calling it in the displayData() method. It is only necessary to call the parent's constructor explicitly in the subclass constructor if you do additional work in the subclass constructor. Inheriting it directly without changes means you needn't call the parent constructor.
Calling the parent constructor will not return a value (object), as instantiating the object would.

Are abstract class constructors not implicitly called when a derived class is instantiated?

Take this example:
abstract class Base {
function __construct() {
echo 'Base __construct<br/>';
}
}
class Child extends Base {
function __construct() {
echo 'Child __construct<br/>';
}
}
$c = new Child();
Coming from a C# background, I expect the output to be
Base __construct Child __construct
However, the actual output is just
Child __construct
No, the constructor of the parent class is not called if the child class defines a constructor.
From the constructor of your child class, you have to call the constructor of the parent's class :
parent::__construct();
Passing it parameters, if needed.
Generally, you'll do so at the beginning of the constructor of the child class, before any specific code ; which means, in your case, you'd have :
class Child extends Base {
function __construct() {
parent::__construct();
echo 'Child __construct<br/>';
}
}
And, for reference, you can take a look at this page of the PHP manual : Constructors and Destructors -- it states (quoting) :
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.
Well, I just found this in the docs:
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.
If you need the same behaviour as C#, that is the parent constructor gets always executed before child constructor, you could create a fake constructor class for your child classes and declare it as an abstract function in your abstract parent class.
E.g.
abstract class Test{
abstract public function __childconstruct();
public function __construct(){
echo "SOME CODE".PHP_EOL;
$this->__childconstruct();
}
}
class TestExtended extends Test{
public function __childconstruct(){
echo "SOME OTHER CODE FROM EXTENDED CLASS".PHP_EOL;
}
}
$a = new TestExtended();
/* SOME CODE
SOME OTHER CODE FROM EXTENDED CLASS */

Categories