PHP空构造函数

13

我在思考,在 PHP 中最好是定义一个空构造函数还是完全省略构造函数的定义?我的习惯是仅使用 return true; 定义构造函数,即使我不需要构造函数做任何事情 - 只是为了完整性而已。

6个回答

11

如果你不需要构造函数,最好将其省略,没有必要写更多的代码。当你确实需要编写它时,请将其留空...返回true没有任何意义。


7

两者有所不同:如果你编写一个空的__construct()函数,那么它将覆盖任何来自父类的继承的__construct()函数。

所以,如果你并不需要它,并且不想显式地覆盖父构造函数,那么根本不用写它。


5

编辑:

之前的答案已经过时,因为PHP现在的行为类似于其他面向对象编程语言。构造函数不是接口的一部分。因此,您现在可以随意覆盖它们而不会出现任何问题。

唯一的例外是:

interface iTest
{
    function __construct(A $a, B $b, Array $c);
}

class Test implements iTest
{
    function __construct(A $a, B $b, Array $c){}
    // in this case the constructor must be compatible with the one specified in the interface
    // this is something that php allows but that should never be used
    // in fact as i stated earlier, constructors must not be part of interfaces
}

之前不再有效的答案:

空构造函数和没有构造函数之间有重要区别。

class A{}

class B extends A{
     function __construct(ArrayObject $a, DOMDocument $b){}
}

VS

class A{
     function __construct(){}
}
class B extends A{
    function __construct(ArrayObject $a, DOMDocument $b){}
}

// error B::__construct should be compatible with A constructor

不仅如此,如果A有一个已定义的构造函数并且B有一个已定义的空构造函数,那么您实际上将删除构造函数,但是如果您完全省略它,则会继承父级构造函数。结果是,您不应该“总是”或“从不”包含空构造函数,并且当您执行其中之一时,它并不总是意味着相同的事情。这一切都取决于上下文。 - Jason

3

只有在您的对象永远不应被实例化时才应定义空构造函数。如果是这种情况,请将__construct()私有化。


1
构造函数总是返回其所定义的类的实例。因此,在构造函数内部永远不会使用"return"关键字。最后,如果不打算使用它,最好不要定义构造函数。

构造函数的返回值完全被忽略。 - KingCrunch
1
如果我发现有人在构造函数中返回,那么我绝不会将他的代码与我的合并。 - Mr Coder

0

你可能想定义一个空构造函数的原因是当你想避免调用与类名相同的函数时。

class FooBar {
    function foobar() {
        echo "Hello world";
    }
}
new FooBar(); // outputs "Hello world" in  PHP < 8

这是由于 PHP 4 向后兼容性,其中构造函数与类名相同的原因。无论如何,在 PHP 7.4.26 中已被弃用。

class FooBar {
    function __construct() {
    }
    function foobar() {
        echo "Hello world";
    }
}
new FooBar(); // no output

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接