Why does PHP not automatically call parent constru

2019-02-07 19:41发布

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.

3条回答
我只想做你的唯一
2楼-- · 2019-02-07 19:46

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?

查看更多
Emotional °昔
3楼-- · 2019-02-07 19:50

When you don't have a constructor in the child class, then the parent one is automatically called.

If you decided to add a constructor to the child class, then of course you need to explicitly call the parent constructor. If you are already taking the time to add a constructor to your child class, then adding one more line of code parent::__construct(); doesn't seem to be a big deal. But the overriding is actually a convenient flexibility.

查看更多
smile是对你的礼貌
4楼-- · 2019-02-07 19:56

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.

查看更多
登录 后发表回答