PHP中全局变量和函数参数的优缺点?

问题描述:

抱歉,我是初学者,我无法确定这是一个多么好的问题,也许对你们中的一些人来说这听起来很明显.

sorry i'm a beginner and i can't determine how good a question this is, maybe it sounds utterly obvious to some of you.

如果我们使用下面这两个是一样的,哪个更好?

if our use of these two below is the same which is better?

function doSomething ($var1,$var2,..){
    ...
}

function doSomething (){
    global $var1,$var2,..;
    ...
}

我们使用的意思是我知道在第二种情况下我们也可以改变全局变量的值.但是如果我们不需要这样做,那么编写这个函数的更好方法是什么?传递变量是否比在函数中声明全局变量占用更少的内存?

by our use I mean that I know that in the second scenario we can also alter the global variables' value. but what if we don't need to do that, which is the better way of writing this function? does passing variables take less memory than announcing global's in a function?

内存使用是一个微不足道的问题.更重要的是代码易于遵循并且没有……不可预测的……结果.从 IMO 的角度来看,添加全局变量是一个非常糟糕的想法.

The memory usage is a paltry concern. It's much more important that the code be easy to follow and not have... unpredicted... results. Adding global variables is a VERY BAD IDEA from this standpoint, IMO.

如果您担心内存使用情况,可以做的是

If you're concerned about memory usage, the thing to do is

function doSomething (&$var1, &$var2,..) {
   ...
}

这将通过引用传递变量,而不是在内存中创建它们的新副本.如果在函数执行过程中修改它们,这些修改会在执行返回给调用者时反映出来.

This will pass the variables by reference and not create new copies of them in memory. If you modify them during the execution of the function, those modifications will be reflected when execution returns to the caller.

但是,请注意,出于内存原因,即使这样也是必要的,这是非常不寻常的.使用 by-reference 的通常原因是我上面列出的原因(为调用者修改它们).要走的路几乎总是简单的

However, please note that it's very unusual for even this to be necessary for memory reasons. The usual reason to use by-reference is for the reason I listed above (modifying them for the caller). The way to go is almost always the simple

function doSomething ($var1, $var2) {
    ...
}