Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe alternatives to PHP Globals (Good Coding Practices)

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!

like image 621
ShaneC Avatar asked Sep 03 '11 03:09

ShaneC


People also ask

Why does good programming practice avoid global variables?

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.

Should I use global variables in PHP?

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.

What can you do instead of a global variable?

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.

Where are PHP GLOBALS stored?

global variables are stored in the $GLOBALS associative array. It will print "global" and then "local".


1 Answers

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:

  • localizing/encapsulating/namespacing functionality (the function body has no implicit dependencies to the outside world anymore and vice versa, you can now rewrite either part without needing to rewrite the other as long as the function call doesn't change)
  • allows unit testing, since you can test functions in isolation without needing to setup a specific outside world
  • it's clear what a function is going to do to your code just by looking at the signature
like image 170
deceze Avatar answered Nov 07 '22 19:11

deceze