全局与PHP中的静态变量 [英] Global vs static variables in PHP
问题描述
我正在用PHP创建一个基本框架。我需要将当前页面的数据传递给不同的功能,允许他们修改并保存它,然后将其传回到要显示的页面。我原本计划将数据存储在像 $ GLOBALS ['data']
这样的全局变量中,但我开始认为使用全局变量是一个坏主意。所以我在想,相反,我会在系统类中放入一个静态变量,并使用 system :: $ data
来访问它。所以,我的问题是,哪个更好,为什么?
这个:
$ GLOBALS ['data'] = array();
$ GLOBALS ['data'] ['page_title'] ='家';
echo $ GLOBALS ['data'] ['page_title'];
或者:
类系统
{
public static $ data = array()
}
函数数据($ new_var)
{
system :: $ data = array_merge(system :: $ data,$ new_var);
data(array('page_title'=>'Home'));
echo system :: $ data ['page_title'];
全局变量和 public static
变量。类变量命名空间好一点点,但这几乎没有什么区别。在任何时候任何地方都可以访问这两者,并且都是全球性的。
碰巧,我刚写了一篇关于这个主题的详尽文章:
< a href =http://kunststube.net/static/ =noreferrer>如何不使用Statics杀死你的测试性能
I'm creating a basic framework in PHP. I need to pass data for the current page into different functions, allow them to modify and save it, and then pass it back to the page to be displayed. I was originally planning on storing the data in a global variable like $GLOBALS['data']
, but I'm starting to think that using a global is a bad idea. So I'm thinking that instead I will put a static variable in the system class, and access it using system::$data
. So, my question is, which would be better and why?
This:
$GLOBALS['data'] = array();
$GLOBALS['data']['page_title'] = 'Home';
echo $GLOBALS['data']['page_title'];
Or this:
class system
{
public static $data = array()
}
function data($new_var)
{
system::$data = array_merge(system::$data, $new_var);
}
data(array('page_title' => 'Home'));
echo system::$data['page_title'];
There really is no difference between a global variable and a public static
variable. The class variable is namespaced a tiny bit better, but that hardly makes any difference. Both are accessible anywhere at any time and both are global state.
As it happens, I just wrote an exhaustive article on the subject:
How Not To Kill Your Testability Using Statics
这篇关于全局与PHP中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!