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

冷暖自知 提交于 2019-12-21 20:58:15

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/2830334/how-can-i-see-a-variable-defined-in-another-php-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!