PHP:致命错误:无法实例化抽象类 [英] PHP: Fatal error: Cannot instantiate abstract class

查看:694
本文介绍了PHP:致命错误:无法实例化抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象数据库类,名为:

I have an abstract database class named as:

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 ...

中实例化抽象类my_database

我想做的是:抽象类数据库具有受保护的$ value,我想创建一个包装器类,以便能够(临时)更改受保护的值。

What I try to do is: The abstract class database has a protected $value and I would like to create a wrapper class, to be able to change the protected value (temporarily).

我该怎么做?

编辑1:不幸的是,较早时,当我尝试不使用抽象my_database时,出现了错误:

unfortunately earlier, when I tried without abstract my_database, I got the errors:

- abstract methods and must therefore be declared abstract or implemented
- Abstract function cannot contain body

EDIT2:
从my_database中完全取出抽象词后,出现以下错误:

After taking out the abstract word completely from my_database, I got the following error:


致命错误:类my_database包含32个抽象方法,因此必须将
声明为抽象方法或实现其余方法

Fatal error: Class my_database contains 32 abstract methods and must therefore be declared abstract or implement the remaining methods

如何解决此问题?

推荐答案

定义为抽象的类可能无法实例化,并且至少包含一个抽象方法的任何类也必须是抽象的。您可以在以下PHP文档中阅读有关此内容:链接

Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. You can read about this in PHP's documentation here: 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";
    }
}

用这样的类扩展您的抽象类(请注意,所有抽象方法都必须在具体类中定义):

Extend your abstract class with a class like this (note that all abstract methods MUST be defined in concrete class):

class ConcreteClass1 extends AbstractClass
{
    protected function getValue() {
        return "ConcreteClass1";
    }

    public function prefixValue($prefix) {
        return "{$prefix}ConcreteClass1";
    }
}

然后,您可以创建ConcreteClass1的实例:

Then you can create instance of ConcreteClass1:

$class1 = new ConcreteClass1;

这篇关于PHP:致命错误:无法实例化抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆