I have a problem with the below:-
//index.php
<?php
define('PATH','Ajfit/');
/* Get all the required files and functions */
require(PATH . 'settings.inc.php');
require(PATH . 'inc/common.inc.php');
?>
//setting.inc.php
<?php
$settings['language']='English';
?>
//inc/common.inc.php
<?php
//global $settings, $lang, $_SESSION; //$setting = null????
$language = $settings['language']; //$language is still null
?>
when i try and access the global variable $settings within common.inc.php it is set null even though i set the variable within setting.inc.php. If i debug, when i step out of setting.inc.php the $settings valiable is set within the index.php, however when i step into common.inc.php the $settings valiable is set to null.
Does anyone have any ideas?
Answer: In the
inc/common.inc.phpfile, you don’t need to use theglobalkeyword, the variable is already accessible. Usingglobalredefines the variable, and is thus madenull.Explanation:
Variable Scope is the key here. The
globalkeyword is only required when scope changes. The scope of regular files (includinginclude()s) is all the same, so all of your variables are accessible by any php in the same scope, even if it comes from a different file.An example of where you need to use
globalis inside of functions. The scope of a function is different than that of plain php, which is different fromclassscope, and so on.Example:
More Information:
If you want more information on when to use
globaland when not to, check the php.net documentation on variable scope.