抽象类是否有可能强制其子类在 PHP 中具有构造函数


Is it possible for an abstract class to force it's children to have a constructor in PHP?

我想做这样的事情:

abstract class Foo
{
    public function __construct()
    {
        echo 'This is the parent constructor';
    }
    abstract function __construct();
}
class Bar extends Foo
{
    // constructor is required as this class extends Foo
    public function __construct() 
    {
        //call parent::__construct() if necessary
        echo 'This is the child constructor';
    }
}

但是这样做时我遇到了一个致命错误:

Fatal error: Cannot redeclare Foo::__construct() in Foo.php on line 8

有没有另一种方法可以确保子类具有构造函数?

简而言之,没有。没有一个神奇的方法可以通过抽象关键字声明。

如果要使用构造函数的旧方法,请创建一个与类同名的方法,并将其声明为抽象方法。这将在类实例化时调用。

例:

abstract class Foo
{
    public function __construct()
    {
        echo 'This is the parent constructor';
    }
    abstract function Bar();
}
class Bar extends Foo
{
    // constructor is required as this class extends Foo
    public function Bar() 
    {
        parent::__construct();
        echo 'This is the child constructor';
    }
}

不过,我建议为您的功能使用接口。