为什么不使用全局(美元符号 $)变量? [英] Why aren't global (dollar-sign $) variables used?

查看:56
本文介绍了为什么不使用全局(美元符号 $)变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 Rails 周围进行了一年半的黑客攻击,我非常喜欢它!:)

在 Rails 中,我们大量使用了局部变量、实例变量(如 @user_name)和初始化器中定义的常量(如 FILES_UPLOAD_PATH).但是为什么没有人使用像 $dynamic_cluster_name 这样的全局美元化"变量 ($)?

是因为设计缺陷吗?和性能有关吗?安全漏洞?

解决方案

是因为设计缺陷问题吗?

设计... 缺陷?那是设计的祝福,设计的恩惠,设计的优点,除了缺陷之外的一切!全局变量不好,而且它们在 Web 应用程序中尤其不好.

使用全局变量的意义在于保持并改变全局状态".它在简单的单线程脚本中运行良好(不,不好,它运行糟糕,但是,仍然可以运行),但在 Web 应用程序中则不然.大多数 Web 应用程序运行并发后端:即通过公共代理和负载平衡器响应请求的多个服务器实例.如果您更改全局变量,它只会在 一个 服务器实例中被修改.本质上,当您使用 Rails 编写 Web 应用程序时,美元符号变量不再是全局的.

然而,全局常量仍然有效,因为它们是常量,它们不会改变,并且在不同的服务器中有几个它们的实例是可以的,因为它们在那里总是相等的.>

要存储可变全局状态,您必须使用更复杂的工具,例如数据库(SQL 和 noSQL;ActiveRecord 是访问数据库的一种非常好的方式,请使用它!)、缓存后端(memcached),甚至是普通文件(在极少数情况下它们很有用)!但是全局变量根本不起作用.

I'm hacking around Rails for a year and half now, and I quite enjoy it! :)

In rails, we make a lots of use of local variables, instance variables (like @user_name) and constants defined in initializers (like FILES_UPLOAD_PATH). But why doesn't anyone use global "dollarized" variables ($) like $dynamic_cluster_name?

Is it because of a design flaw? Is it performance related? A security weakness?

解决方案

Is it because of design flaw issue ?

Design... flaw? That's a design blessing, design boon, design merit, everything but flaw! Global variables are bad, and they are especially bad in Web applications.

The sense of using global variables is keeping—and changing—the "global state". It works well in a simple single-threaded scripts (no, not well, it works awful, but, still, works), but in web apps it just does not. Most web applications run concurrent backends: i.e. several server instances that respond to requests through a common proxy and load balancer. If you change a global variable, it gets modified only in one of the server instances. Essentially, a dollar-sign variable is not global anymore when you're writing a web app with rails.

Global constant, however, still work, because they are constants, they do not change, and having several instances of them in different servers is OK, because they will always be equal there.

To store a mutable global state, you have to employ more sophisticated tools, such as databases (SQL and noSQL; ActiveRecord is a very nice way to access the DB, use it!), cache backends (memcached), even plain files (in rare cases they're useful)! But global variables simply don't work.

这篇关于为什么不使用全局(美元符号 $)变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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