Home » Php » php – Set Global variable from Controller function

php – Set Global variable from Controller function

Posted by: admin February 25, 2020 Leave a comment

Questions:

i am working on CI project where i am stuck somewhere. I try to set a global variable value from function and access this value from other function. Here is my code..

class Example extends CI_Controller {

    public $gData = "";

    public function userinfo() {
        //Here i fetch user infomration from database table 
        $userName = "userName";
        $this->gData = $userName;
    }

    public function getuserinfo() {
        echo $this->gData;
    }

}

userinfo is my actual page which opens in browser, and fetch data of user from user table. On my view i have button on click of button i am calling ajax which call the getuserinfo method of controller, it suppose to return the username which i set in userinfo method but unfortunetly it not working. Any will plz guide me where i am making mistake. (I am not allowed to use session)

How to&Answers:

try this: You have to set user name first in global variable:

class Example extends CI_Controller {

    public $gData = "";

    public function userinfo() {
        //Here i fetch user infomration from database table 
        $userName = "userName";
        $this->gData = $userName;
    }

    public function getuserinfo() {
       $this->userinfo();
        echo $this->gData;
    }

}

OR you can use constructor: I am not familiar with CI

class Example extends CI_Controller {

        public $gData = "";

         Public function __construct() { 
         parent::__construct(); 
         $this->userinfo();
      } 

        public function userinfo() {
            //Here i fetch user infomration from database table 
            $userName = "userName";
            $this->gData = $userName;
        }

        public function getuserinfo() {

            echo $this->gData;
        }

    }

Edited Answer:
Based on comment the solution can be like this if you don’t want to use session :

1. Create a view using the Query of userinfo.

2. Create a model using that view and write your logic.
I think this may help you . It will not slow down your result.

Answer:

You can define the variable in the constructor as Amitesh stated or you could change your userinfo() method to just return data so the getuserinfo() method can use it. For example:

class Example extends CI_Controller {

    public function userinfo() {
        //Here i fetch user infomration from database table 
        $userName = "userName";
        return $userName;
    }

    public function getuserinfo() {
        // get the data
        $username = $this->userinfo();
        echo $username;
    }

}

By calling $this->userinfo() you’ll be running that method and the return value will be available to any function (within the same controller) who makes the call