kai*_*ser 6 php oop constructor
我正在寻找一种从子类自动神奇地调用父类构造函数(?)的方法:
(注意:这只是一个示例,因此可能存在输入错误)
Class myParent()
{
protected $html;
function __construct( $args )
{
$this->html = $this->set_html( $args );
}
protected function set_html( $args )
{
if ( $args['foo'] === 'bar' )
$args['foo'] = 'foobar';
return $args;
}
}
Class myChild extends myParent
{
public function do_stuff( $args )
{
return $this->html;
}
}
Class myInit
{
public function __construct( $args )
{
$this->get_stuff( $args );
}
public function get_stuff( $args )
{
$my_child = new myChild();
print_r( $my_child->do_stuff( $args ) );
}
}
$args = array( 'foo' => 'bar, 'what' => 'ever' );
new myInit( $args );
// Should Output:
/* Array( 'foo' => 'foobar', 'what' => 'ever' ) */
Run Code Online (Sandbox Code Playgroud)
我想避免的是必须调用(在类myChild中)__construct( $args ) { parent::__construct( $args ); }.
问题:这可能吗?如果是这样:怎么样?
谢谢!
在您的示例代码中,myParent :: __构造将被称为wen instanciating myChild.要让代码按照您的意愿工作,只需更改即可
public function get_stuff( $args )
{
$my_child = new myChild();
print_r( $my_child->do_stuff( $args ) );
}
Run Code Online (Sandbox Code Playgroud)
通过
public function get_stuff( $args )
{
$my_child = new myChild($args);
print_r( $my_child->do_stuff() );
}
Run Code Online (Sandbox Code Playgroud)
只要myChild没有构造函数,就会调用/继承父构造函数.
由于Child没有构造函数存在和扩展 Parent,new Child()所以指定任何时间都Parent将隐式调用构造函数.
如果确实指定了Child构造函数,则必须parent::__construct();在Child构造函数内使用指定,因为它不会被隐式调用.
NB在子类中定义构造函数时,最佳做法是调用parent::__construct()方法定义的第一行,以便在子类启动之前设置任何实例参数和继承状态.