3

I'm planning to expose some common variables as globals in my script and am wondering if the following naming scheme would be considered bad ideas:

  1. using single underscore at the beginning and end like: $_some_var_
  2. using triple underscore at the beginning like: $___some_var

I know that php uses single underscore at the beginning for superglobals and double underscore for magic methods so there shouldn't be any conflicts. Is there anything else that could cause trouble? And is doing this considered bad for any other reason?

Thanks!

4
  • 5
    Yes, using globals is considered bad. There is also a proper way of implementing the same things without globals Commented Apr 30, 2012 at 22:41
  • 1
    @zerkms: I think the OP is asking about the underscores, not usage of globals in general... But yes, globals are bad mkay! Commented Apr 30, 2012 at 22:42
  • Why are globals so frowned upon? From my understanding the only reason to avoid using globals is to avoid naming conflicts, is there any other reason to avoid it? BTW the reason I'm doing this is to store a database read that will be used pretty much everywhere on the page (user info), so I thought it made sense to read it once and store it as a global. Commented Apr 30, 2012 at 23:29
  • 1
    The major issue with globals is that you cannot control it. You don't know where it is instantiated and where and how it is modified Commented Apr 30, 2012 at 23:56

3 Answers 3

1

It won't cause any problems per say. For ease of typing you may just want to go with the single underscore.

In my app, if I must introduce such globals that I may use in many scripts both inside and outside of functions, I use the $GLOBALS superglobal so it is very apparent that the variable being accessed is a global.

This also saves having to use global $somevar; in functions. But it is a lot more typing depending on how often you use them.

Could the values possible be constants or are they actually variable?

Sign up to request clarification or add additional context in comments.

2 Comments

I totally forgot php globals isn't included in the local scope, you probably saved me some debugging time later, thanks!
:) Excellent, I mentioned it because I've fallen victim to it a number of times. It's very easy to forget!
0

If you really think you need global state, how about creating a static class instead?

class myVars {

  static property $var1;

}

Comments

0

If they are to be treated as constants then use: define("CONSTANT_NAME", value)

If they are truly global variables, then one convention is: $mVariableName

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.