0

I'm using Netbeans IDE, it shows a warning next to undeclared variables - very useful.

If I have this at the top of a file

global $CFG;

then the warnings go away because the variable has been declared.

But is this good practice? Are they any advantages? The code still works without the declaration.

Note: This is for files that have code outside of functions.

4

3 回答 3

1

it is good practice to declare variables before using them. Declaring them as global within the global scope is superfluous though. You could just do

Instead of doing

global $CFG;

you can just do

$CFG;

The only time declaring them with the global prefix is "useful" is when you do it inside a function to access a globally scoped variable from within the function - but this is usually bad practice, very few cases where this is absolutely necessary.

于 2013-03-10T23:00:22.300 回答
0

No, if you wish to use a variable outside of its scope (for example inside a function) you may pass it or globalize it inside the function

function xoxo(){
   global $var;
}
于 2013-03-10T22:59:32.213 回答
0

有两件事让我对以这种方式“声明”变量保持警惕。

首先,任何函数之外的大量代码可能意味着您的代码需要重构。在您的代码的顶层,您可能有几行调用脚本或页面的主要操作,但是说您的声明将放在“文件的顶部”表明还有更多。

其次,在 PHP 中“声明”一个变量通常与赋予它某种初始值同义。例如,$params = array()在构建模板参数列表之前进行设置,例如$params['foo'] = get_foo(). 这种初始化应始终与使用它的代码保持接近,这样如果您稍后重新分解它,代码就会随之而来。

为什么总是初始化一个变量是一个好主意的一个例子是,如果你最终将整个代码块放在某种循环中。在上面的例子中,如果我渲染了多个模板并且忘记了初始化$params$params['foo']最终可能会被传递给每个模板。

于 2013-03-10T23:27:42.660 回答