PHP中全局变量和函数参数之间的优缺点? [英] The advantage / disadvantage between global variables and function parameters in PHP?

查看:81
本文介绍了PHP中全局变量和函数参数之间的优缺点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

下面这两个是相同的哪个更好?

 函数doSomething($ var1,$ var2 ,..){
...
}

OR

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

我的意思是我知道在第二种情况下,我们也可以改变全局变量的值。但是如果我们不需要这样做,那么这是写这个函数的更好方法呢?内存使用是一个微不足道的问题。通过变量传递的变量占用的内存少于在函数中声明全局变量的内存吗? 解决方案

更重要的是,代码容易遵循,并且不会有......不可预测的结果。从这个角度来看,添加全局变量是一个非常糟糕的IDE,IMO。



如果你关心内存使用情况,那么要做的是

 函数doSomething(& $ var1,& $ var2,..){
...
}

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



然而,请注意,即使这样,由于记忆原因是必要的。由于我上面列出的原因(修改它们给调用者),使用by-reference的通常原因是。要走的路几乎总是很简单的

 函数doSomething($ var1,$ var2){
...
}


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,..){
    ...
}

OR

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?

解决方案

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.

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) {
    ...
}

这篇关于PHP中全局变量和函数参数之间的优缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆