How to fix var-use-before-def-global PHP5 error within included files

Posted On Oct 19, 2008 at 7:48 am

var-use-before-def-global : Global variable $id was used before it was defined

If you make use of the code analyzer available in many modern IDE environments when coding strictly to PHP5 standards, you may have noticed that you will get errors thrown at you for using variables before they are declared in included files. For example, lets say you have two files, header.php and index.php.

<? echo $someVariable; ?> <? $someVariable = "someValue"; include('header.php'); ?>

If you analyzed header.php, you would get an error that says Global variable $someVariable was used before it was defined. This is easily fixed by defining the variables with the global type. Example:

<? global $someVariable; echo $someVariable; ?>

This will let the analyzer know that this variable pre-exists in the environment without changing its value.

As with other variable declarations in PHP5, you can define a whole set of variables without having to repeat the variable type over and over.

<? global $someVariable1, $someVariable2, $someVariable3, $someVariable4; ?>

This topic has the following tags: