I'm working with PHP to build an MVC in order to understand how one works.
After establishing the basic framework, I had the idea to define common variables in a file that is included in my initialization file (index.php
) and accessible by all subsequent files. After researching, and a ridiculous amount of trial and error, I've found a way to accomplish this.
Visual:
##common.php
# a file of variables used in my project.
$myvar1 = value1;
$myvar2 = value2;
etc...
I initially tried to reference the variables in the common.php file as if they were defined on the page in which they were to be used, yet discovered this did not work.
Visual:
##page.php
# another page in the same project
# where common.php is included.
//get the value of $myvar1
print $myvar1; // *this does not return value1*
Now I am referencing the variables as part of the $GLOBALS
array.
##page.php
print $GLOBALS['myvar1'] // *returns value1*
These are variables, thus I did not use define(constant, value)
.
Is my method correct, is there another correct way to do this, or perhaps I'm totally off base?