PHP function not callable

The past 3 hours I'm scratching my head with the following problem. My Database class:

<?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;
    }

  }

When I call Database::getInstance()->test('Hello') I get the following error

PHP Fatal error: Call to a member function test() on a non-object in ...

I checked for proper pdo connection, no problem with that. The output of var_dump(Database::getInstance()) is NULL.

What I am doing wrong ?

1 answer

  • answered 2018-02-13 01:13 Elias Soares

    You are missing a return on your getInstance()

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

    instead you should do:

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

    or:

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