开发者

How can I see a variable defined in another php-file?

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.开发者_Python百科 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.


That is exactly how it works.

Have you got error reporting set up, and is there anything in the error log? I'm guessing the include is failing but you're not seeing the error.


Have all your pages start in the one file that defines the parameters and then dispatch to the respective sub pages. This way the variables defined in first file will exist in all included pages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜