For years I have used global $var,$var2,...,$varn
for methods in my application. I've used them for two main implementations:
Getting an already set class (such as DB connection), and passing info to functions that display to page.
Example:
$output['header']['log_out'] = "Log Out";
function showPage(){
global $db, $output;
$db = ( isset( $db ) ) ? $db : new Database();
$output['header']['title'] = $db->getConfig( 'siteTitle' );
require( 'myHTMLPage.html' );
exit();
}
There are, however, performance and security ramifications of doing it like this.
What alternative practice can I use that will maintain my functionality but improve design, performance, and/or security?
This is the first question I've ever asked on SO, so if you need clarifications please comment!
Global variables are generally avoided because they threaten “encapsulation”, or in other words, the ability of the script to control the ability to access information inside an object.
There is no need to do global $variable; to access it within functions or methods. Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.
In a scenario, where you need one central global point of access across the codebase, singletons are a good alternative for global variables. We can call a singleton as a lazily initialized global class which is useful when you have large objects — memory allocation can be deferred till when it's actually needed.
global variables are stored in the $GLOBALS associative array. It will print "global" and then "local".
The alternative is called dependency injection. In a nutshell it means that you pass the data a function/class/object requires as parameters.
function showPage(Database $db, array &$output) {
...
}
$output['header']['log_out'] = "Log Out";
$db = new Database;
showPage($db, $output);
This is better for a number of reasons:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With