Gapton
Gapton

Reputation: 2134

PHP superclass and subclass

A simple question, does the following make sense ?

Class B extends Class A

class A constructor:

function __construct(){
    //do something
}

Class B constructor:

function __construct(){
    parent::__construct();
}

Is there any significant advantage to implementing the child constructor at all in this case?

I can only think of :

Would be interesting to know if there is any significant advantages in coding or in structuring etc.

Upvotes: 0

Views: 3132

Answers (3)

deed02392
deed02392

Reputation: 5022

A local constructor overrides its parent:

<?php
class Blog extends CI_Controller {

       public function __construct()
       {
            parent::__construct();
            // Your own constructor code
       }
}
?>

If you have a __construct() method in the child class you must call the parent constructor explicitly.

If you have no desire to run anything in the child constructor, do not specify the constructor method in the child and the parents constructor will be called automatically.

Upvotes: 0

Thomas Clayson
Thomas Clayson

Reputation: 29935

The only time you want to invoke your parent constructor from your subclass (child class) is when you want to add custom code in your constructor.

In your example you can leave out the __construct() method altogether in Class B.

However you might want to do something like this:

class A {

  function __construct() {
    run_a_function();
    $this->set = "a variable";
  }

}

class B {

  function __construct() {
    run_a_function_specific_to_class_b();
    $this->set = "a variable specific to class b";

    // now call the parent constructor
    parent::__construct();
  }

}

Upvotes: 4

deceze
deceze

Reputation: 522402

No. If all your constructor (or any method for that matter) does is call the parent method of the same name, then there's no advantage whatsoever. Just more lines of code.

Upvotes: 0

Related Questions