I use the same constant in all my php files. I do not want to assign the value of this variable in all my files. So, I wanted to create one "parameters.php" file and to do the assignment there. Then in all other files I include the "parameters.php" and use variables defined in the "parameters.php".
It was the idea but it does not work. I also tried to make the variable global. It also does not work. Is there a way to do what I want? Or may be there some alternative approach?
I'm guessing you're trying to use the global variables within a function body. Variables defined in this fashion are not accessible within functions without a global declaration in the function.
For example:
$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'
}
The other option, as Finbarr mentions, is to define a constant:
define('FOO', 'bar');
function printFoo() {
echo "Foo is '" . FOO . "'"; //prints: Foo is 'bar'
}
Defining has the advantage that the constant can't be later overwritten.
See PHP define: http://php.net/manual/en/function.define.php
define("CONSTANT_NAME", "Constant value");
Accessed elsewhere in code with CONSTANT_NAME. If the values are constant, you are definitely best to use the define function rather than just variables - this will ensure you do not accidentally overwrite your variable constants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With