简体   繁体   English

PHP如何确保父类被构造

[英]php how to ensure that parent class gets constructed

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 . 而且据我所知,构造函数应该是public

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM