Functions and php include

@AirFor, look, most PHP users confuse the real disastrous usage of this operator with rather innocent use case.

What is a real sin and should be always avoided is tossing local variables between functions like this:

function1() {
  global $var;
  $var = 1;
}
function2() {
  global $var;
  echo $var;
}
function1();
function2();

this should be avoided at any cost, and always written as

function1() {
  $var = 1;
  return $var;
}
function2($var) {
  global $var;
  echo $var;
}
$var = function1();
function2($var);

While for a really global service it is no harm to use it. if it’s sort of constant that have to be globally available - why not to use global then?

But so strong is a superstitious disgust to globals, that people tend to avoid it at any cost, and reinvent wheels instead, with same meaning, but different look.

Well, the above has a touch of trolling. Even real global variables still bear some drawbacks.

First, they are writable. Means in some part of code you may accidentally set it to null and then wondering, why it stopped working elsewhere.

Another problem is that sometimes you need several services of the same kind, say, more than one db handler. One single global variable is not that flexible. That is why it is generally recommended to send all function variables as parameters - this way you will have more control on them, injecting the exact srrvice you need in this very function call.

Well, back to connection. Please take a look at the suggestion I made in the recent thread on the same topic

3 Likes