Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
抽象类是否可以强制它';让孩子们在PHP中拥有构造函数?_Php_Oop_Constructor_Abstract Class - Fatal编程技术网

抽象类是否可以强制它';让孩子们在PHP中拥有构造函数?

抽象类是否可以强制它';让孩子们在PHP中拥有构造函数?,php,oop,constructor,abstract-class,Php,Oop,Constructor,Abstract Class,我想这样做: 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 pub

我想这样做:

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关键字声明非魔术方法

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

例如:

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

不过,我建议您在功能上使用接口。

抽象类不会强制这样做,但接口会。您为什么要这样想?我理解给定方法的需要,但是构造函数呢?@Sebas你可以用一个脚本做数十亿件事情,你不认为仅仅其中一个就需要一个构造函数吗?是的,当然,但从我的过去来看,强制一个类扩展另一个类来实现构造函数有点奇怪!我相信你有你的理由,不必担心,是的,我想这种方法会奏效,但在我的实际应用程序中有许多类继承自
Foo
。感谢您提供的信息,我们将使用一个界面。