如何在Codeigniter中从库中访问Controller中声明的静态变量?

问题描述 投票:-1回答:1

我想访问在Codeigniter Controller中声明的静态变量,我想在库中使用它。这是代码。

控制器位置和名称:

姓名:Console

地点:./application/controllers/Console.php

图书馆位置和名称:

姓名:Api

地点:./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);
    }
}

正如我所描述的,我想访问在Console类中声明的静态变量到这里我使用过##### CALL_STATIC_VARIABLE_HERE ######

我尝试过这样的事情:(我知道它不会起作用,我是对的)

Console::$developer_secret - 不工作

self::$CI->Console::$developer_secret - 不工作

self::$CI->Console->$developer_secret - 不工作

php codeigniter codeigniter-3 static-variables
1个回答
0
投票

为什么不将这些变量放在配置文件中?

application/config文件夹中创建一个PHP文件。无论你想要什么,都可以命然后将变量放在文件中,如下所示。

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

如果要添加另一个变量

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

保存文件后,请在库中加载配置文件。

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

现在在任何你想要的地方使用$myvar。希望这可以帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.