1

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 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.