qadenza
qadenza

Reputation: 9293

how to make a variable global only in one place

$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);

function abc(){
    global $db;
    ...
}

function xyz(){
    global $db;
    ...
}

Let's say I have 100 functions which uses $db.

Is it the true that I must 100 times write global $db?

Is there a way to access $db in all functions automatically, like in javascript?

Upvotes: 1

Views: 88

Answers (5)

evilReiko
evilReiko

Reputation: 20473

As everyone already said, you have to use the keyword global to avoid mixing with local variables:

function my_func() {
    global $db;
    ...
}

If you really need a global variable, one possible way is to use the $_GLOBALS:

$_GLOBALS['db'] = $db;    

function my_func() {
    $_GLOBALS['db']->...;
    ...
}

It's better to use OOP, but sometimes, a developer needs to write a quick script that do stuff, and PHP is a good choice for this. If you don't want to go OOP-way and still want to use global variables in many functions, here's a workaround.

1- Create a file, let's call it my_globals.php that has this content:

// my so many globals stay here
global $db;
global $a;
global $b;
...

2- In your main file, you would do something like this:

$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$a = ...;
$b = ...;

function abc(){
    include 'my_globals.php';// this will be equivalent as typing all your global variables
    ...
}

function xyz(){
    include 'my_globals.php';// this will be equivalent as typing all your global variables
    ...
}

Upvotes: 1

Thamilhan
Thamilhan

Reputation: 13313

You can otherwise use super global $GLOBALS['db'] directly inside your function without the need to declare every time.

Only for this reason we use Object Oriented Approach or some libraries like medoo.


Update: (From one of your comments)

You nay need to understand the Scope of the Variable to know its advantage before calling so.

Upvotes: 1

Rajapandian
Rajapandian

Reputation: 216

If need to access variable, then yes, you have to add global in all your functions or use $_GLOBALS

since you are using function, better to create static class

class DB {
   private static $db       = null;
   public static function connect() {
     if(!empty(self::$db)) {
       return self::$db;
     }
     self::$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
    }
}

Access db using DB::connect()->query();

Upvotes: 1

aidinMC
aidinMC

Reputation: 1426

You can pass $db as parameter to functions or use $GLOBALS['db']

function abc($db){
    $db->query();
}

or

$GLOBALS['db'] = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
function abc (){
   $GLOBALS['db']->query();
}

Upvotes: 1

Sage Harpuia
Sage Harpuia

Reputation: 356

as far I know, there no way to do such thing, you need to declare global $db in every function you wanna use it

Upvotes: 1

Related Questions