Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

variables - PHP global or $GLOBALS

Is there a best practice / recommendation when I want to use a variable declared outside of a function when it comes to using:

  1. global $myVar
  2. $GLOBALS['myVar']

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, you should only use globals in limited circumstances, but to answer your question:

  1. global is potentially marginally faster (it will rarely make a difference).
  2. $GLOBALS (not $GLOBAL) is more readable, because every time you see it, you know you are accessing/changing a global variable. This can be crucial in avoiding nasty bugs.
  3. Inside the function, if you want to unset a global variable, you must use unset($GLOBALS['varname']), not global $varname; unset($varname);.

As to points 1 and 2, I'll quote Sara Golemon here:

What does that mean for your use of the $GLOBALS array? That's right, the global keyword is technically faster. Now, I want to be really clear about one thing here. The minor speed affordance given by using your globals as localized [compiled variables] needs to be seriously weighed against the maintainability of looking at your code in five years and knowing that $foo came from the global scope. something_using($GLOBALS['foo']); will ALWAYS be clearer to you down the line than global $foo; /* buncha code */ something_using($foo); Don't be penny-wise and pound foolish..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...