Wern Ancheta
Wern Ancheta

Reputation: 23297

What to use instead of global in php

Is there any other way instead of using global everytime I need to access a global variable inside a function?

$db = new ezSQL_mysql("root", "", "payroll", "localhost");

class employee{
  function get_emp(){
    global $db;

  }
}

Upvotes: 2

Views: 1304

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270599

In normal global-scope functions, either use the global keyword, or $GLOBALS['db'] superglobal array (which is preferable for readability). The other alternative is to pass the global variable into the function as a parameter.

In your class, the best method is dependency injection. Your class constructor receives the $db as a parameter, which makes it available to all class methods:

// $db was created at global scope
$db = new ezSQL_mysql("root", "", "payroll", "localhost");

class employee {
  public $db;

  // $db already created in your script is passed as a dependency
  // to the class constructor
  public function __construct($db) {
    $this->db = $db;
  }

  // Access it as $this->db inside the class
  public function get_emp() {
    do_something($this->db);
  }
}

Upvotes: 6

Related Questions