0

Ok this may be a simple/noobish question but can't figure out...

I have a class, wich i include in another php script.

So, i call for example $user->login, but if i want to create a function and use this variable $user or any other variable defined outside the function, i need to declare it GLOBAL inside the function.

Is there a way to declare it GLOBAL only one time, outside functions, instead to declare it in every function i need?

3 Answers 3

3

Not really, no. You can do a few horrible things depending on the situation, but in general, just use global. If you find that this is becoming a problem, you probably have too many globals or are using them for the wrong reasons, and you should consider putting things into classes (e.g.) instead.


And, just for the heck of it, said horrible things are as follows (in order of horror):

  • Make user a function and call it every time you need the $user global
  • Make user a class and refer to everything statically with a shared state, since PHP usually doesn't have threads anyways
  • Use runkit to get that variable treated as a superglobal
  • Overwrite an existing superglobal
Sign up to request clarification or add additional context in comments.

2 Comments

minitech, out of interest as i have seen this in a few codebases, whats the horror of your first non-suggestion?
@RickBurgess: It is usually the wrong way to go about things. If there is no alternative, it can be an acceptable choice of style, but the functions are sometimes better off being in classes - from what I've seen, that's usually what they represent. (But maybe that doesn't work for projects like Wordpress? [Not that everyone agrees it's structured ideally :)])
1

... if i want to create a function and use this variable $user or any other variable defined outside the function...

You don't need globals here. Pass the variable to your function. Or pass it to your class constructor and store it inside a property. Then you can access that property in every method of your class

Comments

0

Well, all globals are accessible through $GLOBALS['var_name'] so you could use $GLOBALS['user']->login but you will soon prefer declaring global $user.

Then you'll add $user as a parameter to your function.

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.