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

时间:2014-11-11 10:16:25

标签: php oop dependency-injection

我有一个Connection课程,可以连接到特定的" Service"。在实例化类时,您可以调用特定的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()   第18行的C:\ Users。\ Documents ... \ Service.php

问题

  • 出现此错误的原因是什么?
  • 如何解决此错误?
  • 如何从扩展Service类?
  • 的类中调用函数

1 个答案:

答案 0 :(得分:1)

为了使其正常工作,您需要将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关键字。

相关问题