Classes that extend other classes inherit the same constructor?

For instance...

if I have a module class:

class Module{

  var $page;

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

and then the specific class of the news module:

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

Can I create a news as follows:

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

or should I do this:

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

Thank.

PS: I am completely new to OOP php, so bear with me lol. I switched from procedural php to objective-c and now back to object php .: p It is very difficult to try to compare with each other.

+3
source share
4 answers

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

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

class Bar extends Foo {
}

At startup:

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

However, if you define a custom constructor for your class, it will not call the Foo constructor. Be sure to call parent::__construct()in this case.

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

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

( vs __construct).

+4

News, function News($page) {...}, : parent::Module($page). $page, .

+1

PHP, , . News .

0

__construct() , .

, , .

, . , News, , $page parent::__construct($page);

, , , , $page . var PHP 4, $page . . , News aFunction?

0

All Articles