Global keyword out of function in php

As you know, a global keyword makes a variable (or an object, an array) visible inside the current function with which we are dealing

<?php $some_var = 'some string'; function __test(){ global $some_var; echo $some_var; // some string } 

But some developers still use the global keyword outside functions at first glance it does not make any sense to me.

Well, the question is, does it make sense to use the "global" keyword outside the function ???

+7
source share
2 answers

From docs :

Using a global keyword outside a function is not a mistake. It can be used if the file is included inside the function.

Essentially, you can have your function in a different file than the declaration of your function. These guts will then be included in the function. This will give the impression that if you look only at the guts of a user using global outside the function, the fact is that when this code is interpreted, it will be interpreted from within the function.

 $name = "Jonathan"; function doSomething () { include( 'functionGuts.php' ); } 

If the contents of our functionGuts.php file could be:

 global $name; echo "Hello, " . $name; 

When viewed on its own, functionGuts.php will give the impression that global used outside the function, when in fact it is used as follows:

 $name = "Jonathan"; function doSomething () { global $name; echo "Hello, " . $name; } 
+7
source

A global keyword does nothing outside functions. but this file can be included in the function.

Another thing I'm using is not to make my codes readable and more structured. any variable that I want to get using the global keyword in the function, I declare it with global in the main file, so just take a quick look, and I know that it is referred to somewhere as global. (that is, do not rename, as others are used somewhere else ... :))

0
source

All Articles