全局变量与局部变量 [英] Global Variables vs. Local Variables

查看:97
本文介绍了全局变量与局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我不确定我是否正确理解了这个概念(正在学习PHP).如果我正确理解: 全局变量可以在同一文档中或与"include"链接的文档中的任何地方引用.局部变量只能在它们所在的函数中引用.

Okay, I'm not sure I'm understanding this concept properly (I'm learning PHP). If I understand correctly: Global variables can be referenced anywhere in the same document, or in documents linked with "include." Local variables can only be referenced in the function where they are.

好的,如果我理解正确(那是我发布的一半,以确保我有权利),那么确实需要局部变量吗?我的意思是,如果每个用户都定义了自己的变量,并且需要全部保存它们,那么我会发现它很有用……是什么?但是,我认为使用数据库会更简单.我想在什么情况下使用局部变量?

Okay, if I understand that correctly (which is half of the reason I'm posting, to make sure I have that right) is there really a need for local variables? I mean, if each user defined their own variables and they needed to all be saved, I can see it being useful... kind of? But, using a database for that would be much simpler I'd think. What situations would I want to use local variables in?

推荐答案

您的问题一直很有意义,直到您要求 local 变量的需求.总体而言,应尽可能避免使用全局变量.

You're question was making sense right up to the point where you asked for the need of local variables. On the whole, you should avoid global variables as much as you can.

我经常写一些工具/webapp,并且只有两个或三个 own 全局变量用于设置实际的应用程序.

It's not uncommon for me to write some tool/webapp and have only two or three of my own global variables, that I use to set the actual application in motion.

考虑一下:

$db = new PDO($conn, $usr, $pass);
function select(array $fields, $tbl, $where = '')
{
    global $db;//use the global variable
    return $db->query('SELECT '.implode(', ', $fields).' FROM '.$tbl.' WHERE '.$where);
}

就其本身而言,您可能会争辩说此代码将一直正常工作.很清楚$db是什么,因此这里没有明显错误.
但是,假设您还包含其他两个使用相同的$db var的文件,并且其中一个文件中存在一个错误,导致重新分配了$db:

In itself, you might argue that this code will work fine all the time. It's clear what $db is, and so there's no obvious error here.
However, suppose you include a couple of other files that use the same $db var, and there's a bug in one of those files, that causes $db to be reassigned:

$db = 'I used to be a PDO instnace';
select(array('*'), 'tbl');

这将显示一个错误,将您指向读取return $db->query();的行,并显示类似试图调用非对象的方法" 之类的内容.

This will show an error that will point you to the line that reads return $db->query(); and it'll say something like "trying to call method of non-object".

祝您调试顺利! $db在哪里重新分配了?除了逐步筛选代码外,没有其他方法可以知道.

Good luck debugging that! Where was $db reassigned? there's no way to know except for sifting through your code step by step.

它可能仍然是您上次离开它的地方,但是它的状态(或值)很可能已被可能使用了您的钱包(或变量)的其他一些实体/实体(人员或代码)改变了(显着).作为他们自己的,幸福的,没有意识到你把它留在那儿,以备将来参考.在编写类或函数时,您指的是将这些代码也用作用户的同事.因此,即使对他们没有害处,全球性事件也是一个意外,等待发生.

It might still be where you last left it, but chances are its state (or value) has been changed (significantly) by some other entity/entities (people or code), who might have used your wallet (or variable) as their own, blissfuly unaware you left it there for future reference. When writing classes or functions, you refer to your collegues who will use that code as the user, too. So even if they meant no harm, a global is an accident, waiting to happen.

顺便说一句,函数参数局部变量,所以我确定您已经在使用它们,却并不了解.

Incidentally, the function arguments are local variables, so I'm sure you're using them already, without knowing it.

最好如下定义select函数:

function select(PDO $connection, array $fields, $tbl = 'tbl', $where = null)
{
    $query = 'SELECT '.implode(', ', $fields).' FROM '.$tbl;
    $query .= $where !== null ? ' WHERE '.$where : '';
    return $connection->query($query);
}

在此函数中,我创建了一个局部变量,以使代码更具可读性/可维护性.就像我说的那样,所有参数也是局部变量,因此在该函数返回之后,可以释放为适应其持有的值而分配的任何内存.使用全局变量时,垃圾收集器无法执行其工作,因为这些变量仍在作用域内,并且可能在代码中进一步使用.仅在脚本完成运行后才释放内存.

In this funciton I've created a local variable to make the code more readable/maintainable. Like I said, all the arguments are local variables, too, so after this function returns, any memory that was allocated to accomodate the values they held can be freed. When you're using global variables, the Garbage Collector can't do its job, because the variables remain in scope, and might be used further down the code. The memory is only freed once the script has finished running.

全局变量(全局范围内的变量)会产生混乱的代码,当您尝试避免名称冲突时,您会发现自己声明了$i_for_looping_over_array1 = 0;

Globals (vars in the global scope) make for messy code, as you try to avoid name conflicts, you're going to find yourself declaring vars like $i_for_looping_over_array1 = 0;

好吧,这可能有点极端,但是无论如何,您最终都将使用伪命名来命名var,所以为什么不使用 proper 命名空间,作用域,类等呢?

Ok that might be a bit extreme, but you'll end up pseudo-namespacing your vars anyway, so why not use proper namespaces, scopes, classes, etc.?

每当在函数内使用global关键字时,您实际上是在说:寻找一个名为$someName的变量,该变量可以在任何地方.将相同的变量作为参数传递,就是告诉函数使用此.

Whenever you use the global keyword inside a function, you're effectively saying: look for a variable called $someName, which can be anywhere. Passing that same variable as an argument, is telling the function use this.

传递对象时,实际上是传递对该对象的引用(即其地址),因此不需要查找.复制基元,因此也没有查找.

When passing an object, you're actually passing a reference to that object (ie its address), so there's no lookup required. Primitives are copied, so there's no lookup either.

想想自己是一名调酒师.您想在哪里工作? Pub AllIsGlobalHere,在您的第一天,老板就说:如果客户要东西,瓶子可以在任何地方,地窖,地板或右上角的橱柜",或Pub CheckTheArguments.后者是您跳进去的地方,当客户要啤酒时,您的老板和/或客户会帮助您指出应参考的草案.

Think of yourself as a bartender. Where would you rather work? Pub AllIsGlobalHere, where, on your first day, your boss said: "If a customer asks for something, the bottle could be anywhere, the cellar, the floor or the top-right cupboard", or Pub CheckTheArguments. The latter being the place where you jump right in, and when a customer asks for a beer, your boss and/or customer helpfully point out which draught you should refer to.

这篇关于全局变量与局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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