我有一个关于简单的PHP类扩展的问题.当我有这个父类时:
<?php
class Parent
{
protected $_args;
public function __construct($args)
{
$this->_args = $args;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我想扩展使用:
<?php
class Child extends Parent
{
public function __construct($args)
{
parent::__construct($args);
/* Child constructor stuff goes here. */
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我使用以下方法调用此子类:
new Child($args);
Run Code Online (Sandbox Code Playgroud)
这一切都没有任何问题,但问题是:是否有可能在子节点中有一个"干净"的构造函数,而不必将所有构造函数参数传递给父级?我看到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...
}
}
Run Code Online (Sandbox Code Playgroud)