简体   繁体   中英

How to access static variable declared in Controller from Library in Codeigniter?

I want to access the static variable declared in Codeigniter Controller and I want to use it in the Library. Here is the code.

Controller Location & Name:

Name : Console

Location : ./application/controllers/Console.php

Library Location & Name:

Name : Api

Location : ./applications/libraries/Api.php


Console.php

class Console extends CI_Controller {

    public static $access_agents = [
        '2017_app_v1.0',
        '2017_api_v1.0'
    ];

    public static $developer_secret = [
        'HTTP_X_DEVELOPER_SECRET' => 'XYZ'
    ];

}

Api.php

class Api
{

    public static $CI;

    public function __construct()
    {
        self::$CI = & get_instance();
    }

    public static function print_services_list($list)
    {
        if(self::get_custom_header(##### CALL_STATIC_VARIABLE_HERE ######))
        $array = [
            'status' => '200',
            'message' => 'OK',
            'text' => "List of APIs under this Interface gateway.",
            'data' => $list
        ];
        self::print_json_array($array);
    }
}

As I described I want to access the Static variable declared in Console Class into here where I have used ##### CALL_STATIC_VARIABLE_HERE ######

I have tried things like these: (I knew it wouldn't work probably and I was right)

Console::$developer_secret - NOT WORKING

self::$CI->Console::$developer_secret - NOT WORKING

self::$CI->Console->$developer_secret - NOT WORKING

Why don't you place these variables in the config file?

Create a PHP file in application/config folder. Name it whatever you want. Then place your variables in the file as below.

<?php
$config['static_var']['your-static-variable-name'] = 'Whatever value you want to initialize'

If you want to add another variable

<?php
    $config['static_var']['your-another-static-variable-name'] = 'Whatever value you want to initialize'

Once the file is saved please load the config file in your library.

class Api
{
    protected $CI;
    protected $my_var;
    protected $my_another_var;

    public function __construct()
    {
         $this->CI =& get_instance();
         $this->CI->load->config('your config file name');
         $this->my_var = $this->CI->config->item('your-static-variable-name','static_var');
         $this->my_another_var = $this->CI->config->item('your-another-static-variable-name','static_var');
    }
}

Now use $myvar wherever you want. Hope this can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM