PHP question about global variables and function arguments

Status
Not open for further replies.

Lord Pachelbel

Ars Praefectus
5,499
Subscriptor++
Suppose there's a global object called $user which refers to the currently-logged-in user.

Consider this example function:
Code:
function example_function() {

  global $user; // reference the global user object

  echo $user->id;

}

Now suppose that I'm logged in with an admin account, but I want to call this function and have it do stuff to a different user account, for debugging purposes or whatever. Inside the function, it possible to override the global $user with a function argument?

E.g.
Code:
function example_function($user) { // can this argument...
  global $user; // ...override this declaration?

  echo $user->id;
}

if($DEBUG) {
  example_function($a_different_user_than_the_admin_who_is_logged_in);
}
 

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
Code:
// "$GLOBALS" is a superglobal that contains all the global variables
YOU: global variables
ME: global variables are the worst thing to happen to programming

YOU: superglobal
ME: *rubs temples slowly*

Sometimes you get in worse shape trying to fight predominate patterns in a language or framework :shrug:

Also, sometimes you are working on legacy stuff and you just need something to work. Not every, in fact I'd say most, projects are not greenfield. Today's new hotness is tomorrow's legacy, yadda yadda yadda.
 
Status
Not open for further replies.