How can I see a variable defined in another php file?
I use the same constant in all my php files. I don't want to assign the value to this variable in all of my files. So, I wanted to create one file "parameters.php" and do the job there. Then in all other files I have include
"parameters.php" and use the variables defined in "parameters.php".
It was an idea, but it doesn't work. I also tried making a variable global
. It also doesn't work. Is there a way to do what I want? Or maybe some alternative approach?
a source to share
See PHP definition: http://php.net/manual/en/function.define.php
define("CONSTANT_NAME", "Constant value");
Available elsewhere in the code with CONSTANT_NAME
. If the values are constant, you are by far the best way to use a function define
rather than just variables - this ensures that you don't accidentally overwrite the constant variables.
a source to share
I am assuming you are trying to use globals inside the body of the function. Variables defined in this way are not available in functions without a global declaration in the function.
For instance:
$foo = 'bar';
function printFoo() {
echo "Foo is '$foo'"; //prints: Foo is '', gives warning about undefined variable
}
There are two alternatives:
function printFoo() {
global $foo;
echo "Foo is '$foo'"; //prints: Foo is 'bar'
}
OR:
function printFoo() {
echo "Foo is '" . $GLOBALS['foo'] . "'"; //prints: Foo is 'bar'
}
Another parameter, as Finbarr mentions , is to define a constant:
define('FOO', 'bar');
function printFoo() {
echo "Foo is '" . FOO . "'"; //prints: Foo is 'bar'
}
The definition has the advantage that the constant cannot be overwritten later.
a source to share