Search code examples
phpsessionfat-free-framework

Undefined variable error php even after variable is set


I have defined a variable $userStatus globally in a class, and the value is to be overridden [when a option is selected in drop-down]. The variable is overridden by a session value that is set when the drop-down is changed. When the session is not set, the function is working fine.. but when the drop-down is changed and the session is set, Undefined variable $userStatus is displayed. Here is what I tried:

protected $userStatus = 1;

public function export($f3, $params)
{
    if(null !== ($this->f3->get('SESSION.userStatus')))
    {
        $this->$userStatus =  $this->f3->get('SESSION.userStatus');
    }
    $rowID = 5;
    foreach ($results as $result) 
       {
          if($this->userStatus == 2)
             {
                //logic
             }
          else{ //.... }
          $rowID++;
       }
}

Here's how the session is set with ajax:

public function updateUserStatus($f3)
    {
        $status = $this->f3->get('POST.status');
        $this->f3->set('SESSION.userStatus', $status);
        echo $status;
    }

NOTE:

  • export function is run with default $userStatus value.
  • when the value is changed, session is set and $userStatus value is supposed to be overridden
  • now when the user clicks "Export" button, the export function is run again, with the session value set. that's when the variable is unrecognized.

I just wanted to set a default value for $userStatus, otherwise, it is working fine when the dropdown is changed. Please where did I do wrong?


Solution

  • You have a typo.

    Change from this

    $this->$userStatus
    

    With this:

    $this->userStatus
    

    Also change this

    if(null !== ($this->f3->get('SESSION.userStatus')))
    

    With this:

    if(!empty($this->f3->get('SESSION.userStatus')))