Variable Scope: Accessing variable in first function from second function


Well-known member
I'm creating a custom pages and this is my actionIndex:
public function actionIndex()
$maxUserId = XenForo_Application::get('db')->fetchRow("SELECT MAX(user_id) FROM xf_user");
$randUser = rand(1, $maxUserId['MAX(user_id)']);
$user = $this->getModelFromCache('XenForo_Model_User')->getUserById($randUser);
$viewParams = array(
'user' => $user

return $this->responseView('MyAddon_ViewPublic_Index', 'MyAddon_Index', $viewParams);
This code selects the highest user ID from the database and uses it as the highest value for the rand() function ($randUser variable). It then uses the random number as a user ID which is put in the getUserById function to return a user based on the random ID.

The user is then returned in the viewparams as $user.

This works fine, it spits out a result etc.

My next code:
public function actionAvatarCheck()
$data = $this->_input->filter(array(
'username' => XenForo_Input::STRING

$viewParams = array( 'data' => $data );
return $this->responseView('MyAddon_ViewPublic_AvatarCheck', 'MyAddon_Check', $viewParams);
This code works fine so far. It returns the user input (single text field) and puts it into the viewparams for use in templates - fine.

Now what I'm trying to do is compare the user input ($data['username']) in the actionAvatarCheck() function to the $user variable in the actionIndex() function.

In layman's terms: I want the $user variable in the first function to be available in the second function. I have no idea about variable scope and this is why I'm asking :D


Active member
I'm not familiar with XenForo code, but I understand what each action method is doing.

However, I don't understand the relationship between the two? Are the two methods occurring in separate processes?

Basically, I am wondering if the issue is truly scope or a matter of making the random generated id persistent.


Well-known member
The randomly generated ID is generated at actionIndex(), but the user input isn't checked until actionAvatarCheck() so I was hoping to pull the $user variable from actionIndex() to actionAvatarCheck(). My workaround method is to re-define the $user variable, but I didn't really want to have to pull the model from the cache in both functions.


Well-known member
You'll have to, think of it as running the XenForo program twice.

The first time you run it you do actionIndex, then the program quits. Then you run it again and do actionAvatarCheck. Typically to do stuff like this you pass the id from actionIndex to a form element, then when they submit it picks it up from the form element.


Well-known member
I was hoping to define the variable outside of the function. Thanks SheepCow!