I share the PHP code base across all pages and for each HTTP request I dynamically require the "/configs/$site/config.php" file. The file looks like this:
<?php
$SiteConfiguration = [
'site_title => 'Wiki for Developers',
'mysql_host' => 'localhost',
'mysql_db' => 'wiki-devs',
'articles_per_page' => 10,
/* ... etc ... */
];
?>
The problem I’m facing is that I can’t quite access this variable from functions.
For example:
function DisplayArticles() {
echo "Displaying ".$SiteConfiguration['articles_per_page'];
}
It will print just Displaying and not Displaying 10.
How can I fix this and have my $SiteConfiguration accessible everywhere? Should I use a class? What’s the best practice here?
put
in your function, you can find some more info at http://www.php.net/manual/en/language.variables.scope.php
Since you asked for best practice info: (simplest form)
then in your code you can recall it with
and use it. (obviously with a better, more descriptive name than MySite 😉 )
Advantages:
in my opinion it beats globals and it beats passing via arguments since it’s cleaner and you control the access to it in all forms. You can make certain attributes readonly/writable via specific getter/setter options, keep count of how many times it’s accessed and whatever else you can think of.