【问题标题】:Is it possible for an abstract class to force it's children to have a constructor in PHP?抽象类是否可以强制其子类在 PHP 中具有构造函数?
【发布时间】:2012-06-25 08:35:44
【问题描述】:

我想做这样的事情:

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

还有其他方法可以确保子类有构造函数吗?

【问题讨论】:

  • 抽象类不会强制这样做,但接口会。
  • 你为什么要这样想呢?我了解给定方法的需求,但是构造函数呢?
  • @Sebas 你可以用一个脚本做数十亿的事情,你不认为其中一个可能需要构造函数吗?
  • 当然可以,但是从我的过去来看,强制一个类扩展另一个类来实现 a 构造函数有点奇怪!我相信你有你的理由,不用担心

标签: php oop constructor abstract-class


【解决方案1】:

简而言之,没有。非魔法方法可以通过 abstract 关键字声明。

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

例子:

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';
    }
}

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

【讨论】:

  • 是的,我认为这种方式可行,但在我的实际应用程序中,有许多类继承自 Foo。感谢您的信息,将使用界面。
猜你喜欢
  • 2010-11-26
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 2018-06-10
相关资源
最近更新 更多