is global in the function normal?

There is a class that works with the database there is a function that returns a specific string, including using the{[2] class]}

The only way to use the class inside the function was using global code example

<?php

$db = new TestClass();

function getContent($param1, $param2){
   global $db;
   return $db->blabla('SELECT ... ', $param1, $param2);
}

Is this normal? or is it better to use something else to define $db inside the function?

Author: ultrabatya, 2016-09-08

1 answers

The ideal answer is a comment from Vladimir Gamalian:

For small scripts, it is quite normal, the benefits of abandoning global are felt with the increasing complexity of the software system.

From myself, I would define it like this:

If, as in this case, the code is written procedurally, then there is nothing wrong with using global in this way.

In general, global is scolded for two reasons. The first is really fear and horror when this operator is not used. as intended, to pass local variables to the function, which disastrously confuses the program. Let's say we have the function

function f1() {
    global $var
    $var++;
}

And somewhere in the program code there is such a piece:

$var = 1;
f1();

What happened to the $var variable, what the f1 () function did-it is absolutely not clear from this code. Such code should always be avoided. Instead of global in this case, you should always write like this:

function f1($var) {
    return $var++;
}

And use

$var = 1;
$var = f1($var);

The second reason is, relatively speaking, the inability to replace $db on the fly.
In more complex software systems, it is sometimes necessary to replace a particular service, depending on the task. For example, instead of mysql, use, say, MongoDB. For the same task, but depending on the context. And in this case, global will become a hindrance, and we will need to invent more complex ways to pass services to a function.

But as long as our program is simple enough, it does not use OOP, and at the same time, we use this operator for truly global services, the use of global is quite justified.

 6
Author: Ипатьев, 2016-09-09 03:51:15