Why shouldnt you use GLOBALS?Loads of forums say dont use GLOBAL variables, however are we saying pass the variables into the functions?
class App {
var $db;
var $anotherVar;
public function connect(){
//your connection code
$this->db=$connection:
}
public function getDb(){
if ($this->db===null) {
$this->connect();
}
return $this->db;
}
}
function getData($id){
App::getDb()->query("...");
....
}
<?php
class db {
public function getDb(){
return "true";
}
}
$dbConn = new db;
echo $dbConn->getDb();
class db2 {
public function test(){
$dbConn->getDb();
}
}
$ttt = new db2();
echo $ttt->test();
?>
<?php
class db {
public function getDb(){
return "true";
}
}
class db2 {
var $db2Conn;
public function __construct($dbConnection) {
$db2Conn = $dbConnection;
}
public function test() {
$this->db2Conn->getDb();
}
}
$dbConn = new db;
echo $dbConn->getDb();
$ttt = new db2($dbConn);
echo $ttt->test();
?>
public function __construct($dbConnection) {
$this->db2Conn = $dbConnection; // Missing $this reference
}
<?php // demo/mysqli_di_example.php
/**
* Demonstrate Dependency Injection with a MySQLi Object
*
* Man Page References:
* http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
* http://php.net/manual/en/mysqli.overview.php
* http://php.net/manual/en/class.mysqli.php
* http://php.net/manual/en/class.mysqli-stmt.php
* http://php.net/manual/en/class.mysqli-result.php
* http://php.net/manual/en/class.mysqli-warning.php
*/
// RAISE THE ERROR REPORTING LEVEL TO THE HIGHEST POSSIBLE SETTING
ini_set('display_errors', TRUE);
error_reporting(E_ALL);
echo '<pre>';
// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";
// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);
// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
$err
= "CONNECT FAIL: "
. $mysqli->connect_errno
. ' '
. $mysqli->connect_error
;
trigger_error($err, E_USER_ERROR);
}
// ACTIVATE THIS TO SHOW WHAT THE DB CONNECTION OBJECT LOOKS LIKE
// var_dump($mysqli);
// A FUNCTION THAT USES AN INJECTED DATABASE CONNECTION
function run_a_query($db, $query)
{
if (!$res = $db->query($query))
{
$err
= 'QUERY FAILURE:'
. ' ERRNO: '
. $mysqli->errno
. ' ERROR: '
. $mysqli->error
. ' QUERY: '
. $sql
;
trigger_error($err, E_USER_ERROR);
}
$data = $res->fetch_object();
return $data;
}
// USE THE FUNCTION BY INJECTING THE $mysqli OBJECT AND THE QUERY
$set = run_a_query($mysqli, 'SELECT 2+2 AS ANSWER');
var_dump($set);
What ever problem you think you are solving by using globals you will find an easier, more logical, solution that does not use them.