troks
troks

Reputation: 91

Instantiate class dependencies with static method

I want to use a static method of an example class without instantiating class. This method uses a dependencie class and is instantiated with __construct method. How can this dependency class be instantiated. Example:

class user {
    protected static $db;

    public function __construct() {
        self::$db = database::getInstance();
    }

    public static function get_user() {
        $user = self::$db->query("sql");
        return $user;
    }
}

I know the solution with autoloader or I could just add self::$db = database::getInstance(); in every static method. Could someone kindly show me better suggestions?

Upvotes: 0

Views: 74

Answers (1)

garoevans
garoevans

Reputation: 155

You can add a static setter and getter for the db object and throw an exception if someone tries to access the getter without calling the setter first:

class User
{
  protected static $db;

  public static function setDB($db)
  {
    self::$db = $db;
  }

  protected static function getDB()
  {
    if (!self::$db) {
      throw new Exception('You must `setDB()` the db object before attempting to get it.');
    }

    return self::$db;
  }

  public static function getUser()
  {
    return self::getDB()->query('sql');
  }
}

User::setDB(database::getInstance());
User::getUser();

Upvotes: 2

Related Questions