【发布时间】:2011-09-20 11:52:11
【问题描述】:
我正在寻找一种从子类自动调用父类构造函数(?)的方法:
(注意:这只是一个示例,因此可能会出现输入错误)
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' ) */
我想避免的是必须调用(在 myChild 类中)__construct( $args ) { parent::__construct( $args ); }。
问题:这可能吗?如果是:如何?
谢谢!
【问题讨论】:
-
你为什么反对打电话给
parent::__construct()? -
我希望 PHP 也能神奇地编写我的应用程序。
-
@Wesley van Opdorp 请查看解决方案。为我工作。 @Charles Sprayberry 我有一个基类,它被未知数量的子类扩展,因此我必须为所有输入参数运行一个标准过程(如删除无效输入、解析默认值等)
标签: php oop constructor