Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do classes which extend other classes inherit the same constructor?

Tags:

oop

php

For instance...

if I have a Module class:

class Module{

  var $page;

  function Module($page){
    $this->page = $page;
  }
}

and then a specific News module class:

class News extends Module {
  function aFunction(){
    return $this->page->id;
  }
}

can I instantiate News like this:

$page = new Page();
$news = new News($page);

or would I have to do this:

$page = new Page();
$news = new News();
$news->page = $page;

Thank you.

PS: I'm quite new to OOP php, so bear with me lol. I've gone from procedural php to objective-c and now back to objective php. :p Its very difficult trying to compare each to the other.

like image 894
Thomas Clayson Avatar asked Dec 06 '25 04:12

Thomas Clayson


1 Answers

Yes, they inherit the constructor. This is something you can easily test yourself. For instance:

class Foo {
  function __construct() {
    echo "foo\n";
  }
}

class Bar extends Foo {
}

When you run:

$bar = new Bar();  // echoes foo

However, if you define a custom constructor for your class, it will not call Foo's constructor. Make sure to call parent::__construct() in that case.

class Baz extends Foo {
  function __construct() {
    echo "baz ";
    parent::__construct();
  }
}

$baz = new Baz();  // echoes baz foo

All of this is true for your old-style constructors, too (name of class vs __construct).

like image 99
Nathan Ostgard Avatar answered Dec 08 '25 18:12

Nathan Ostgard