I am working on a new PHP project now, this time I want to get the basics right at the beginning. Previously I’ve found requiring/including files in php a bit of pain, please consider the following structure:
/application_root/index.php
/js/...
/css/...
/php/...
/conf/...
...
In the index.php I can certainly use something like:
<link rel="stylesheet" href="css/sample.css" ... />
<script type="text/javascript" src="js/sample.js"></script>
To refer to the included css and js, or even php snippets. However, this would only work in the index.php which resides under the root of my application folder. I reckon this is no good.
I came across Java application configuration file “web.xml” where you can define application scope variables that you can simply refer to. .NET with C# has a similar thing. How to achieve this in simple php code so that from any php file in my app, I can type:
<?php echo "<link href='".$application_root_url."/php/sample.css' ..."; ?>
And it will evaluate to the right location?
I am thinking to use:
- Global variables <== bad practice as violation to OOP? I stop doing this since c programming;
- set_include_path <== so php will look for it, requires unique name and proper naming convention?
- load variables from ini files? <== how to make this happen?
- any new thoughts?
You don’t want to use global variables because they break encapsulation.
set_include_pathwill do no good especially if you are using those variables in HTML, because the include_path is relative to the application’s filesystem path and not to its base url.Determining the application base paths is generally not done from a configuration file, as it easy to detect when your application has a gateway script. Since those are constant values, it makes sense to define a constant:
If you want to parse INI files however, you could use parse_ini_file, or parse_ini_string (>=5.3.0):