I’m building a PHP application and I’m not quite sure how to store global configuration settings that can be truely accessed anywhere – it seems that content that is included cannot access other content included from the main, starting page. For example, if index.php includes foo.php and bar.php, bar.php don’t have foo.php but index.php has both of them – the included files just can’t refer to the other ones. Is this correct?
If yes, how would I set up something like this up?
index.php
<?php
include 'functions/load.php'
echo getHeader();
?>
functions/load.php:
<?php
include_once 'config.php'
include_once 'header.php'
//loads the includes
?>
functions/config.php:
<?php
//I want to store the site URL here.
$siteURL = "http://127.0.0.1";
?>
functions/header.php:
<?php
function getHeader(){
return "Header for " . $siteURL;
}
?>
How can I set up an config file that can be then accessed anywhere, including inside other included files? Also, is including a file that lists the other includes good practice?
It’s good practice to include a single
bootstrap.phpfile, which will contain all of the necessary requires. The bootstrap should also define an autoloader, which will be able to autoload classes without having to be explicitly required.It isn’t possible to autoload functions though, so file(s) containing functions will need to be required in
bootstrap.phpusingrequire_once(). See this question for other alternatives.Ideally you’d only have a single “entry point” to your application, which is referred to as a “Front Controller”. If so, then you’ll only need to require your
bootstrap.phponce at the top of this file.Edit: Note about configuration
You’d load your configuration within the bootstrap as well. How you do this is up to you…you could just place all your variables directly in
bootstrap.php, or else you could require in your configuration from there. Best practice is to store configuration in a separate file.Configuration via PHP array:
Or you could use an INI file: