为什么 $params 从配置文件中获取值而不是设置为默认值?
Why $params gets the values from configuration file and not the value set as default?
我有一段代码,它是 CI 3.1 的自定义库的一部分:
class NavigationMenu
{
protected $CI;
public function __construct($params = ['config' => 'navigation'])
{
// this is where I read $params as an array of 10 values
// and it shouldn't be since $params has only one key = config
var_dump($params);
$this->CI =& get_instance();
$this->CI->load->helper('url');
$this->CI->config->load($params['config'], true);
$this->CI->load->model('nav_model', 'nav');
}
....
}
文件“navigation.php”具有以下代码:
$config['navigation_open'] = '<ul class="nav">';
$config['navigation_close'] = '</ul>';
$config['item_open'] = '<li>';
$config['item_open_active_class'] = 'active';
我注意到传递给构造函数的 $params
读作:
array (size=10)
'navigation_open' => string '<ul class="nav">' (length=16)
'navigation_close' => string '</ul>' (length=5)
'item_open' => string '<li>' (length=4)
'item_open_active_class' => string 'active' (length=6)
为什么不读作?
array (size=1)
'config' => string 'navigation' (length=10)
编辑
我没有使用库,这意味着没有创建对象,而是自动加载库,简单如下:
config/autoload.php
$autoload['config'] = ['navigation'];
这将导致在我点击应用程序的 index.php 文件时调用 class 构造函数。
这是 CI 的默认行为吗?来自 PHP 构造函数,我不知道吗?或者我的代码有问题而我没有看到它?
您应该改用 $this->CI->config->set_item($params['config'], true)
。请仔细阅读this documentation。
我有一段代码,它是 CI 3.1 的自定义库的一部分:
class NavigationMenu
{
protected $CI;
public function __construct($params = ['config' => 'navigation'])
{
// this is where I read $params as an array of 10 values
// and it shouldn't be since $params has only one key = config
var_dump($params);
$this->CI =& get_instance();
$this->CI->load->helper('url');
$this->CI->config->load($params['config'], true);
$this->CI->load->model('nav_model', 'nav');
}
....
}
文件“navigation.php”具有以下代码:
$config['navigation_open'] = '<ul class="nav">';
$config['navigation_close'] = '</ul>';
$config['item_open'] = '<li>';
$config['item_open_active_class'] = 'active';
我注意到传递给构造函数的 $params
读作:
array (size=10)
'navigation_open' => string '<ul class="nav">' (length=16)
'navigation_close' => string '</ul>' (length=5)
'item_open' => string '<li>' (length=4)
'item_open_active_class' => string 'active' (length=6)
为什么不读作?
array (size=1)
'config' => string 'navigation' (length=10)
编辑
我没有使用库,这意味着没有创建对象,而是自动加载库,简单如下:
config/autoload.php
$autoload['config'] = ['navigation'];
这将导致在我点击应用程序的 index.php 文件时调用 class 构造函数。
这是 CI 的默认行为吗?来自 PHP 构造函数,我不知道吗?或者我的代码有问题而我没有看到它?
您应该改用 $this->CI->config->set_item($params['config'], true)
。请仔细阅读this documentation。