0

コンストラクターをまったく呼び出さなくても簡単にオーバーライドできるため、親クラスが常に構築されるようにする最善の方法は何ですか。

また:これは悪い習慣ですか?

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");
4

1 に答える 1

2

次を呼び出して、親のコンストラクターを明示的に呼び出すことができます。

parent::__construct(<params>);

また、私の知る限り、コンストラクターはpublic.

于 2011-01-24T15:42:35.090 に答える