views:

286

answers:

2

Fairly straightforward question. In C++ the parent constructor will be implicitly called before the child constructor, so what logic is there for PHP not to do things this way?

EDIT: I've got a good answer from Lukman, but I was hoping for more of a reason why there is a difference. Maybe the question should be why does C++ not allow custom calling of parent constructors? I guess that's another question though.

+7  A: 

I think it's a good thing that PHP makes you call parent's constructor manually, because it allows child's constructor such as following:

public function __construct() {
   // set up variables that parent::__construct() requires
   $var1 = get_stuff_from_db();
   $var2 = get_stuff_from_webservice();

   parent::__construct($var1, $var2);

   // continue setting up $this var
   $this->default = 'Default';
   $this->do_some_secret_stuff();
}

Or even:

public function __construct($param) {
   // call differently based on condition
   if (is_array($param))
      $param['id'] = 0;
      parent::__construct($param);
   }
   else {
      parent::__construct($param, 0, TRUE);
   }

   // continue setting up $this var
   $this->default = 'Default';
   $this->do_some_secret_stuff();
}

Meaning, you are free to call the parent constructor anywhere within the child's and you are free to do stuff before and after the call. Ain't that a feature indeed?

Lukman
A: 

to avoid tight coupling that's why inheritance (extend keyword in java) is evil and interface class is prefered see Javaworld article: http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html

Still it would be great if there was some instruction to call the parent at some point with a special keyword like forward but I have not yet seen this in any language (even Rebol) except in an unknown language invented by Paul Allen (yeah the co-founder of Microsoft) which is Openscript.

Rebol Tutorial
calling parent's method? lots of OOP languages have that. Like `parent` prefix in PHP, `super()` in Python, `super` in Java and even using the parent class name like `BaseClass::method()` in C++.
Lukman
ALL OOP have that that's part of OOP :). That doesn't mean you should overuse it.
Rebol Tutorial