【问题标题】:Difference between these two OOP scenarios?这两种 OOP 场景的区别?
【发布时间】:2017-04-02 04:41:06
【问题描述】:

我很困惑这两种情况之间的差异或性能增益。为什么会选择一个而不是另一个?

父类:

class exampleB
{
    public function __construct($arg1, $arg2)
    {
        // Do something with the arguments.
    }
}

儿童A班

class exampleA extends exampleB
{
    public function make($arg1, $arg2)
    {
        parent::__construct($arg1, $arg2);
    }
}

运行第一个示例:

$exampleA = new exampleA();
$exampleA->make('arg1', 'arg2');

第二个例子是:

儿童A类

class exampleA extends exampleB
{
    public static function make($arg1, $arg2)
    {
        return new static($arg1, $arg2);
    }
}

运行第二个例子:

exampleA::make('arg1', 'arg2');

有人能告诉我这两种情况之间的优缺点吗?我之所以有这些示例,是因为我不想重写父类的构造函数。

【问题讨论】:

  • 我也不会使用,$exampleA = new exampleA('arg1', 'arg2'); 是你所需要的,因为exambleB 中的构造函数会被自动调用,只要你不覆盖它。
  • 我不想重写父类中的现有构造函数,这就是我想出这些解决方案的原因。应该加上那个。

标签: php oop inheritance extends late-static-binding


【解决方案1】:

您不应该这样做,而是使用构造函数来初始化对象。对象必须在构造后处于有效状态。

之所以有这些示例,是因为我不想重写父类的构造函数。

那么干脆不要在子类中定义构造函数。

class Parent {
    public function __construct() {
        echo 'parent ctor called';
    }
}

class Child extends Parent {}

new Child(); // echo's parent ctor called

【讨论】:

    【解决方案2】:

    我会选择第二个例子。 Make() 就像一个构造函数,因此应该像一个构造函数一样调用,即静态的。

    在第一个示例中,您创建了两个对象而不是一个。当其他开发人员阅读/维护您的代码时,这可能会造成一些混乱。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 2013-10-13
      • 1970-01-01
      相关资源
      最近更新 更多