PHP函数不可调用

时间:2018-02-13 01:13:44

标签: php

在过去的3个小时里,我抓住了以下问题。我的数据库类:

<?php

class Database {
    private static $_instance = null;

    private $_pdo;


    private function __construct() {
      try {
        $this -> _pdo = new PDO('...'));
      } catch (PDOException $e)
      {
        die($e -> getMessage());
      }
    }

    public static function getInstance() {
      if (!isset(self:: $_instance)) {
        self:: $_instance = new Database();
      } else {
        return self:: $_instance;
      }
    }

    public function test($sql) {
      echo $sql;
    }

  }

当我致电Database::getInstance()->test('Hello')时,我收到以下错误

  

PHP致命错误:在非对象中调用成员函数test()   ...

我检查了正确的pdo连接,没问题。 var_dump(Database::getInstance())的输出为NULL。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您错过了getInstance()

的回复
public static function getInstance()
{
    if(!isset(self::$_instance))
    {
        self::$_instance = new Database(); //here
    }else
    {
        return self::$_instance;
    }
}

你应该这样做:

public static function getInstance()
{
    if(!isset(self::$_instance))
    {
        return self::$_instance = new Database();
    }else
    {
        return self::$_instance;
    }
}

或:

public static function getInstance()
{
    if(!isset(self::$_instance))
    {
        self::$_instance = new Database();
    }

    return self::$_instance;
}