PHP Variable Scope

妖精的绣舞 提交于 2019-12-11 07:25:25

问题


Is there a way to declare a variable so it is available in all functions. Basically I want to call: Global $varName; automatically for every function. And no, I can't use a constant.

I don't think its possible but wanted to ask anyway. Thanks! :D


回答1:


That's pretty oldschool and not recommended. If you want to use variables whereever you want consider using sessions of passing through variables if you're on an object oriented tour ;)




回答2:


There is a $GLOBALS variable and a globals keyword.Check out example 1 and 2 on this page in the documentation.

But using a global variable is usually a sign of bad structure in your code.




回答3:


I don't think variables can be globally visible the way you want bnut functions are.

You can declare two functions to access you data : on for reading, one for writing.

But anyway beware : if you change it from many places you will have hard times understanding what's going on when faced with a bug !



来源:https://stackoverflow.com/questions/1781780/php-variable-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!