我想做这样的事情:
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 :
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';
}
}
不过,我会建议为您的功能使用接口(interface)。
关于php - 抽象类是否有可能强制其子级在 PHP 中拥有构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11166458/