CodeIgniter Forums
Global Variable? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Global Variable? (/showthread.php?tid=71783)



Global Variable? - Hasan Al-Haddad - 09-23-2018

Hello, 
i'm new here and i find it is hard to find an answer at google due to my lacks of grammar or i don't even know what i'm gonna search. I've been thinking this over and over and also with practices but i got nothing. so, i want to ask everybody in this forum about this "global variable or not" thing.

i have a controller, i called it A_Controller and it is look like this:
PHP Code:
class A_Controller extends CI_Controller {

  var 
$global 0;

  public function 
__construct(){
    
parent::__construct();
  }

  public function 
setGlobal($value){
    
$this->global $value;
  }

  public function 
index(){
    echo 
$this->global;
  }



what i want to approach is, when i access /A_Controller/setGlobal/1000 the global variable is set. and i want to see its value at /A_Controller/index. but, i always got the global is 0.


RE: Global Variable? - salain - 09-23-2018

Hi,

This is not working because the controller is reinitialized on the second call.

For this to work you need to use something to keep the value of $global like session or a variable in your view.

Or returning index in your setGlobal should work.


PHP Code:
class A_Controller extends CI_Controller {

  var $global = 0;

  public function __construct(){
    parent::__construct();
  }

  public function setGlobal($value){
    $this->global = $value;
    
$this->index();
  }

  public function index(){
    echo $this->global;
  }





RE: Global Variable? - InsiteFX - 09-24-2018

If you need this like a global then use the static keyword.

PHP Code:
class A_Controller extends CI_Controller {

 
 protected static $global 0;

 
 public function __construct(){
 
   parent::__construct();
 
 }

 
 public function setGlobal($value){
 
   self::$global $value;
 
   $this->index();
 
 }

 
 public function index(){
 
   echo self$global;
 
 }