我有一个名为的抽象数据库类:
abstract class database {
protected $value;
}
我创建了另一个抽象类
abstract class my_database extends database {
public function set_value($value) {
$this->value = $value;
}
}
当我尝试使用它时:
$my_db = new my_database();
我得到错误:
Fatal error: Cannot instantiate abstract class my_database in ...
我尝试做的是:抽象类数据库有一个 protected $value,我想创建一个包装类,以便能够(临时)更改 protected 值。
我该怎么做?
EDIT1:不幸的是,早些时候,当我尝试不使用抽象 my_database 时,出现了错误:
- abstract methods and must therefore be declared abstract or implemented
- Abstract function cannot contain body
编辑2: 从my_database中完全取出抽象词后,出现如下错误:
Fatal error: Class my_database contains 32 abstract methods and must therefore be declared abstract or implement the remaining methods
我该如何解决这个问题?
最佳答案
定义为抽象的类不能被实例化,任何包含至少一个抽象方法的类也必须是抽象的。您可以在此处的 PHP 文档中阅读相关信息:link
这是一个例子。
有一个抽象类(注意抽象方法没有主体——它们不能有主体——它只是一个签名):
abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method. It will be available for all children - they don't have to declare it again.
public function printOut() {
print $this->getValue() . "\n";
}
}
用这样的类扩展你的抽象类(注意所有抽象方法必须在具体类中定义):
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
然后您可以创建 ConcreteClass1 的实例:
$class1 = new ConcreteClass1;
关于PHP: fatal error :无法实例化抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44219423/