2

Due to slowness, ( and also for coding reasons ), I know that the use of global variables should be avoided as much as possible. It's twice as slow and it decreases the understanding & tracking of the code flow. But sometimes, you do need them in your functions. Sometimes, they do get very handy.

To some degree constants can be used. But as the name says it all, they are constants after all and therefore, they cannot totally substitute the use of global variables.

If you were to not use global variables, and you do need to use them due to the functionality they offer, what options would you refer to? What utilities are out there in PHP so that a variable can be tapped into within functions, outside of functions, basically anywhere and everywhere. Set it somewhere and read/modify it somewhere else.

As an example, I can throw in the use of session variables as an alternative.

You may find it weird but a session variable can easily do the trick. It actually does the job better than a global variable; I can initialize my session variable right within my functions and in no time, all other parts of my code is able to work with that session variable. Whereas with the global variables, they must be introduced/defined outside the functions scope ( to be exact, at the top of the page ) before they may get used by other sections. Sessions won't suffer from this limitation. However, it is obvious, that Sessions are not the right tool for the goal at hand.

The question is what other ways are out there to tackle the matter of "setting a variable somewhere and read/modify it anywhere else"?

4

2 回答 2

1

如果您确实需要全局变量,您可以拥有一个使用单例模式的全局类:这里是 PHP 中的单例模式示例http://www.talkphp.com/advanced-php-programming/1304-how -使用-singleton-design-pattern.html

基本上,单例模式只允许在整个应用程序中共享的类的一个实例,本质上为您提供了一个全局类来存储全局变量。

于 2012-07-28T01:52:05.573 回答
1

回答您的问题“问题是还有哪些其他方法可以解决“在某处设置变量并在其他任何地方读取/修改它”的问题?”...这仍然没有抓住重点:您正在定义一个全局变量。如果您正在构建一个需要从任何地方访问变量的应用程序,那么它的设计模式很可能存在固有缺陷。

话虽这么说,要更正确地做可能需要做的事情,您可以构建一个基于 set/get 函数的“Bag”样式类,例如;某些设置。在您需要访问这些设置的任何地方注入该类。

于 2012-07-28T02:03:06.103 回答