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?

+2


a source to share


4 answers


This is how it works.



Do you have an error reporting setup and is there anything in the error log? I am assuming the enable does not work, but you do not see the error.

+3


a source


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.

+4


a source


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.

+4


a source


You have all of your pages start in a single file that defines the parameters and then submits to the appropriate sub pages. This way, the variables defined in the first file will exist in all included pages.

0


a source







All Articles