Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic global array in codeigniter

I want a global array that I can access through controller functions, they can either add or delete any item with particular key. How do I do this? I have made my custom controller 'globals.php' and added it on autoload library.

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  $notification_array = array();
  $config['notification'] = $notification_array;
?>

following function on controller should add new item to my array

function add_data(){
   array_unshift($this->config->item('notification'), "sample-data");
}

after add_data adds to the global array, whenever following function is called from client, it should give the updated array to the client.

function send_json()
{
   header('content-type: application/json');
   $target = $this->config->item('notification');
   echo json_encode($target);
}

But my client always gets empty array. How can I make this happen? Please help.

like image 408
asok Buzz Avatar asked Jul 27 '26 21:07

asok Buzz


1 Answers

Hi take advantage of OOP, like this

// put MY_Controller.php under core directory

class MY_Controller extends CI_Controller{

  public $global_array = array('key1'=>'Value one','key2'=>'Value2'):

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

}

//page controller

class Page extends MY_Controller{

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

function send_json()
{
   header('content-type: application/json');
   $target = $this->global_array['key1'];
   echo json_encode($target);
}

}
like image 164
umefarooq Avatar answered Jul 29 '26 12:07

umefarooq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!