我有一个关于简单的PHP类扩展的问题。当我有这个父类时:
<?php
class Parent
{
protected $_args;
public function __construct($args)
{
$this->_args = $args;
}
}
?>
我想用
扩展它<?php
class Child extends Parent
{
public function __construct($args)
{
parent::__construct($args);
/* Child constructor stuff goes here. */
}
}
?>
我调用这个子类使用:
new Child($args);
这一切工作没有任何问题,但问题是:是否有可能有一个"干净"的构造函数在子,而不必传递所有的构造函数参数给父?我看到Kohana框架使用了这种技术,但我不知道怎么做。
你可以定义一个从父构造函数调用的init()
方法。
class Parent
{
protected $_args;
public function __construct($args)
{
$this->_args = $args;
$this->init();
}
protected function init() {}
}
class Child extends Parent
{
protected function init()
{
// Do stuff...
}
}