Welcome Guest, Not a member yet? Register   Sign In
Global Variable?
#1

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.
Reply
#2

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;
  }


A good decision is based on knowledge and not on numbers. - Plato

Reply
#3

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;
 
 }


What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB