PHP-全局变量的性能和内存问题 [英] PHP - performance and memory issue with global variables

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

问题描述

假设情况: 我正在用php运行一个复杂的网站,并且我使用了很多全局变量.

Hypothetical situation: I'm running a complex site in php, and i use a lot of global variables.

i可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo']$_REQUEST['foo']$_REQUEST['bar']等,并将很多不同的内容放入请求范围内(将这些数据作为适当的用法)请参阅请求本身.

i could store the variables in an existing global scope, say $_REQUEST['userInfo'], $_REQUEST['foo'], and $_REQUEST['bar'] etc. and put a lot of different things into the request scope (which would be appropriate use, as these data refer to the request itself).

我可以在大多数功能中继续使用global $userInfo, $foo, $bar;这样的行.

i could keep using lines like global $userInfo, $foo, $bar; in most of my functions.

这两种解决方案是否都有性能下降或内存使用差异?

is there a performance hit, or a difference in memory usage for either solution?

输入一个字母要容易一些...所以有最佳实践指南吗?

one is a little easier to type... so is there a best-practices guideline?

推荐答案

您的全局变量已经可以在$GLOBALS['foo'], $GLOBALS['bar']等中访问.这清楚地表明,在函数范围内,它们比使用global来自全局范围.关键词.不应以任何有意义的方式影响性能.

Your global variables are already accessible in $GLOBALS['foo'], $GLOBALS['bar'] etc. This is a clearer indication inside function scope that they come from the global scope than using the global keyword. Should not affect performance in any meaningful way.

许多人会告诉您,最佳实践是首先避免使用全局变量,而是通过函数调用和对象构造函数传递变量.

Many will tell you that best practice is to avoid global variables in the first place and instead pass variables through function calls and object constructors.

这篇关于PHP-全局变量的性能和内存问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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