Search code examples
phpsecurityfunctionscopeencapsulation

Why is it considered bad practice to use "global" reference inside functions?


Possible Duplicate:
Are global variables in PHP considered bad practice? If so, why?
global in functions

Edit: question answered in link above.

No, "global" in php is not the same thing as global in other languages, and while it does not introduce any security problems it can make the code less comprehensible to others.


OP:

Project summary - I am writing a web CMS to get my feet wet with PHP / MySQL. In order to break up the code I have a concept of these basic tiers / modules:

Data
- MySQL Tables
- PHP Variables

Function
- SQL - Get / Set / etc
- Frontend - Showing pages
- Backend - Manager

Presentation
- HTML Templates
- Page Content
- CSS Stylesheets

The goal is common enough. Use MySQL to hold site settings and page content, use php to get / manipulate content data for a page being served, then insert into an html template and echo to browser. Coming from OO languages like C# the first problem I ran into was variable scope issues when using includes and functions.

From the beginning I had been writing function-only php files and including them where needed in other files that had existing variable array definitions. For example, ignoring the data tier for a moment, a simple page might generically look like this:

File 1 (page)

$DATA_PAGE = Array
(
  'temp'  = null,
  'title' = null,
  [...]
);

include 'functions.php';

get_data ( 'page.php' );

[...]

run_html ();

File 2 (functions)

function get_data ( $page_name )
{
  global $DATA_PAGE;

  $DATA_PAGE [ 'temp'  ] = 'template';
  $DATA_PAGE [ 'title' ] = 'test page';
  [...]
}

function run_html ()
{
  global $DATA_PAGE;

  echo '<html>';
  echo '<head>';
  echo '<title>' . $DATA_PAGE [ 'title' ] . '</title>';
  [...]
}

I chose this method for a few reasons:

  • The data in these arrays after sql fetch might be used anywhere, including page content
  • I didnt want to have a dozen function arguments, or pass entire arrays

The code runs great. But in every article I find on the subject, the "global" calls in my functions are called bad practice, even though the articles never state why? I thought all that meant was "use parent scope". Am in introducing a security hole into my app? Is there a better method? Thanks in advance.


Solution

  • I think a top reason for avoiding this is that it hides dependencies.

    Your functions get_data and run_html do not advertise in any way that they share data, and yet they do, in a big way. And there is no way (short of reading the code) to know that run_html will be useless if get_data has not been called.

    As the complexity of your codebase grows, this kind of lurking dependency will make your code fragile and hard to reason about.