我正在使用PHP编写OOP应用程序。我希望有一个超类,其他类将从中继承 有没有办法可以确保类本身不能直接实例化?
像:
class Mother {}
class Child extends Mother{}
$child = new Child();//no problemo
$mother = new Mother();//throws exception or dies
答案 0 :(得分:4)
您可以使用仅定义方法但不定义其实现的抽象类。
abstract class Mother
{
public function doSomething();
}
class Child implements Mother
{
public function doSomething()
{
echo 'Hello world';
}
}
$mother = new Mother(); // won't work
$child = new Child(); // works
$child->doSomething(); // echoes hello world
或者,如果您需要实现方法实现(函数执行某些操作但可以重载它们),那么您可以使用受保护的构造函数。
class Mother
{
protected function __construct()
{
echo "Hello World!";
}
}
class Child extends Mother
{
public function __construct()
{
parent::__construct();
}
}
$mother = new Mother(); // won't work, you're trying to access protected method
$child = new Child(); // it'll work echoing "Hello World!"
答案 1 :(得分:3)
有abstract个关键字。
abstract class Mother { }