调用类中扩展当前抽象类的函数


Calling a function in the class that extend current abstract class

我有一个连接到特定"Service"的Connection类。在实例化类时,可以调用特定的Service,例如mysqliPDO

class Connection
{
    private $service;
    private $state = null;
    public function __construct(Service $service) {
        $this->service = $service;
    }
    public function initialize() {
       ....
    }
    public function destruct() {
       ....
    }
    //Maybe some getters and setters
}

Service类中有一个getObject()方法,它包含必须实例化的对象,以便连接到数据库或其他对象。

还有一种getInstance()方法。这用于在getObject方法中返回尚未实例化的对象。

abstract class Service
{
    public static function getInstance() {
        $instance = null;
        if ($instance == null) {
            $instance = self::getObject();
        }
        return $instance;
    }
    /**
     * @return object Returns the object where the service should start from.
     */
    public abstract function getObject();
}

下面是一个Service类的示例。

class MySQLService extends Service
{
    public function getObject() {
        return new mysqli('127.0.0.1', 'root', '', 'db');
    }
}

问题

当使用这样的代码时:

$connection = new Connection(MySQLService::getInstance());
$connection->initialize();

它附带了以下错误:

致命错误:无法在中调用抽象方法Service::getObject()C: ''用户。''文档。。。''第18行上的Service.php

问题

  • 这个错误是怎么出现的
  • 如何解决此错误
  • 如何从扩展Service类的类中调用函数

为了实现这一点,您需要将getObject方法声明为静态方法。

Service:中

public abstract function getObject()

应为:

public static function getObject() {}

(对不起,你不能有一个静态摘要)

MySQLService:中

public function getObject() {

应为:

public static function getObject() {

然后,您可以使用以下命令将调用定向到正确的类:

public static function getInstance() {
    static $instance = null;
    if ($instance == null) {
        $instance = static::getObject();
    }
    return $instance;

}

注意,您也错过了实例变量中的static关键字。