【问题标题】:How to Auto-run construct in parent class without call from child class如何在没有子类调用的情况下在父类中自动运行构造
【发布时间】: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


【解决方案1】:

由于Child 不存在构造函数并且扩展 Parent,因此任何时候指定new Child(),Parent 构造函数都将被隐式调用。 p>

如果您确实指定了Child 构造函数,那么您必须在Child 构造函数中使用指定parent::__construct();,因为它不会被隐式调用。

NB 在子类中定义构造函数时,最好在方法定义的第一行调用parent::__construct(),以便在子类启动之前设置任何继承的实例参数和状态。

【讨论】:

    【解决方案2】:

    在您的示例代码中,myParent::__construct 在实例化 myChild 时已经被调用。 要让您的代码按您的意愿工作,只需更改

    public function get_stuff( $args )
    {
        $my_child = new myChild();
        print_r( $my_child->do_stuff( $args ) );
    }
    

    由

     public function get_stuff( $args )
        {
            $my_child = new myChild($args);
            print_r( $my_child->do_stuff() );
        }
    

    只要 myChild 没有构造函数,就会调用/继承父构造函数。

    【讨论】:

    • 完美。 +1。我不知道我可以将它放入类中并调用父构造函数。谢谢
    • As long as myChild has no constructor, the parent constructor will be called / inherited. 非常感谢!我进行了很多搜索,以找到这个简单的陈述,完美地描述了正在发生的事情!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 2018-03-16
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多