Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a couple of ways of doing that. Global variables is certainly one way and the most looked down upon too. You can create a <a href="http://en.wikipedia.org/wiki/Singleton_pattern#PHP" rel="noreferrer" title="Singleton">Singleton</a> and all other classes that need database access would call upon this singleton.</p> <pre><code>final class Database { private static $connection; public static function getInstance() { if(self::$connection == NULL) { self::$connection = // init your database connection } return self::$connection; } } </code></pre> <p>And use this database connection object in whatever class needs it.</p> <pre><code>class Application { public function displayVar() { echo 'hello world'; } public function getVar() { $db = Database::getInstance(); $sql = foo; $db-&gt;query($sql); } } </code></pre> <p>This is all well for a start and a great step beyond using global variables, but you can do better with <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer" title="Dependency Injection">Dependency Injection</a>. Dependency Injection is a simple concept that if a class has any external dependencies, such as the database connection in your example, you explicitly pass those to the needy class in its constructor or a method. So the new code would look something like Jonathan's solution. A major advantage of using dependency injection is in unit testing, where you can easily replace this actual database object with a mock object and pass it to whoever needs it.</p> <pre><code>class Application { private $db; public function __construct(Database $db) { $this-&gt;db = $db; } public function displayVar() { echo 'hello world'; } public function getVar() { $sql = foo; $this-&gt;db-&gt;query($sql); } } </code></pre> <p>For smaller projects, you can easily do it yourself. For large projects, there are various <a href="http://en.wikipedia.org/wiki/Dependency_injection#Existing_frameworks" rel="noreferrer" title="DI frameworks available for PHP">DI frameworks available for PHP</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload