php如何确保父类被构造
确保父类始终被构造的最佳方法是什么,因为我们可以轻松地重写构造函数而无需调用它们。
另外:这是不好的做法吗?
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");
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");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过以下方式显式调用父级的构造函数:
另外据我所知,构造函数应该是
public
。You can explicitly call parent's constructor by calling:
Also as far as I know, constructors should be
public
.