there is a class that performs work with the database; there is a function that returns a specific string, incl. using class

it was possible to use the class inside the function using global code example

<?php $db = new TestClass(); function getContent($param1, $param2){ global $db; return $db->blabla('SELECT ... ', $param1, $param2); } 

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

  • Determine with the parameter: function getContent($param1, $param2, $db){ or function getContent($param1, $param2, TestClass $db){ ... In general, it’s better to do methods ... You can inherit from TestClass ... You can still in different ways ... But the way you did it - not ice - hide it and not show it to anyone. A better destroy: D - Roman Grinyov
  • using global is awful ... best to use classes. - Stanislav
  • 3
    For small scripts it is quite normal, the benefits of abandoning global are felt with the increasing complexity of the software system. - Vladimir Gamalyan September
  • I think singleton will help you - Vfvtnjd

1 answer 1

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 general, global is scolded for two reasons. The first is really fear and horror, when this operator is used inappropriately, to transfer local variables to a function, which catastrophically confuses the program. Let's say we have a 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 is absolutely not clear from this code. This 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 one service or another depending on the task. For example, instead of using mysql, 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 of passing services to a function.

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