function cf_get_user(){
  global $user;

  $copy_of_user = $user;

  return $copy_of_user;
}

In this case $copy_of_user is just a reference to $user. If you change $copy_of_user than $user is changed as well. This is critical because it seems that this is under false pretense of being a copy where it's really a reference to the original.

The solution... you need to clone the object.

Or, the name of the function seems to be about getting the user. Could it be that you meant to get the global user and want to change that? If so, then the copying should be removed.

Comments

dave reid’s picture

Or you could just encourage people to use $account = user_load($GLOBALS['user']->uid); which also works just fine, no helper function necessary....

thekevinday’s picture

Status: Active » Fixed

Thanks for the catch, I don't use objects very often in PHP and I don't know some of the details like that one.
(I was confused for a while when I didn't know php objects are always passed by reference)

Is not $GLOBALS['user'] the same as saying $global?
Telling people to do the following to load user information is confusing:

<?php
  global $user;

  $account = user_load($user->uid);
?>

For that to work implies that the user information is already available, which it is.
If it is already available, then why the loading of the user information for a second time?
For someone starting drupal programming for the first time, these might be their thoughts.

Also, there are comments like this: http://api.drupal.org/api/drupal/developer--globals.php/global/user/7#co...

Against my argument here, I can see the user_load() being better than accessing the global $user in that the information may change over time and user_load() would more likely be up to date.

This is a very small function so i can understand that there is good reason not to have it.
At the same time, I believe that accessing the current user information to be a place where mistakes are commonly made.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.