最佳实践,重写__construct()而不是提供init()方法 [英] Best practice, overriding __construct() versus providing init() method

查看:119
本文介绍了最佳实践,重写__construct()而不是提供init()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您将对象子类化并想扩展初始化代码时,有两种方法.重写__construct(),并实现您的超类构造函数调用的初始化方法.

When you are subclassing objects and want to extend the initialization code, there are two approaches. Overriding __construct(), and implementing an initialization method that your superclass constructor calls.

方法1:

class foo
{
    public function __construct ($arg1, $arg2, $arg3)
    {
        // Do initialization
    }
}

class bar extends foo
{
    public function __construct ($arg1, $arg2, $arg3)
    {
        parent::__construct ($arg1, $arg2, $arg3);
        // Do subclass initialization
    }
}

方法2

class foo
{
    public function init ()
    {
        // Dummy function
    }

    public function __construct ($arg1, $arg2, $arg3)
    {
        // Do subclass defined initialization
        $this -> init ();
        // Do other initialization
    }
}

class bar extends foo
{
    public function init ()
    {
        // Do subclass initialization
    }
}

Zend Framework的文档似乎不鼓励重载的构造方法,并希望您重载init方法(如果提供),但这在某种程度上对我来说并不适合. Zend还倾向于做一些我不满意的事情,因此我不确定是否应该将其用作最佳实践的例子.我个人认为第一种方法是正确的,但是我经常看到第二种方法,足以怀疑这是否是我真正应该做的.

The documentation for Zend Framework seems to discourage overriding constructors and wants you to override init methods, where provided, but this somehow just doesn't feel right to me. Zend also tends to do a few things that I'm not happy with so I'm not sure if it should be used as an example of best practice. I personally think the first approach is the correct one but I've seen the second approach often enough to wonder if that's actually what I should be doing.

您对覆盖__construct有何评论?我知道您必须谨记要调用超类构造函数,但是大多数程序员应该意识到这一点.

Do you have any comments regarding overriding __construct? I know you have to be careful to remember to invoke the superclass constructor, but most programmers should be aware of that.

我没有使用Zend,只是将其用作鼓励您使用init()而不是覆盖__construct()的代码库示例.

I'm not using Zend, I'm only using it as an example of a codebase that encourages you to use init() instead of overriding __construct().

推荐答案

第二种方法似乎推迟了该问题.

Looks like the second approach is postponing the problem.

如果您有课程:

class bar2 extends bar // which already extends foo
{
  public function init()
  {
    // You should then do anyway:
    parent::init();

    // ...
  }
}

我也将采用第一种方法,更加逻辑和直接,因为无法无休止地避免调用parent::init()parent::__construct().第一种方法,IMO,不那么令人困惑.

I would go for the first approach too, more logical and straightforward, since the parent::init() or parent::__construct() call could not be endlessly avoided. The first approach, IMO, is less confusing.

这篇关于最佳实践,重写__construct()而不是提供init()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆