开发者

php how to ensure that parent class gets constructed

开发者 https://www.devze.com 2023-02-06 16:35 出处:网络
What is the best way to ensure that parent class allways gets constructed, since we can easily override constructors without having to call them at all.

What is the best way to ensure that parent class allways gets constructed, since we can easily override constructors without having to call them at all.

Also: is this bad practice?

abstract class A
{
 // make it final to ensure parent constructor is allways used
 final function __construct($param1)
 {
  // do essencial stuff here with $param1
  // pass construction with remaining args to child
  call_user_func_array(array($this,'init'),开发者_如何学编程array_slice(func_get_args(),1));
 }
 abstract function init();
}

class B extends A
{
 function init($param2)
 {
  // effectively extends parent constructor, no?
 }
}

$obj = new B("p1","p2");


You can explicitly call parent's constructor by calling:

parent::__construct(<params>);

Also as far as I know, constructors should be public.

0

精彩评论

暂无评论...
验证码 换一张
取 消