PHP变量访问

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?

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

... 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

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.