Codeigniter将params传递给函数

AFR*_*FRC 4 php codeigniter

我是OOP的新手,我在理解它背后的结构方面遇到了一些麻烦.我在Codeigniter(模板)中创建了一个库,我在加载时传递了一些参数,但我想将这些参数传递给库的函数.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Template {

    public function __construct($params)
    {
        echo '<pre>'; print_r($params); echo '</pre>';
        //these are the parameters I need. I've printed them and everything seems fine
    }

    public function some_function()
    {
        //I need the above parameters here
    }

}
Run Code Online (Sandbox Code Playgroud)

Wes*_*rch 5

试试这个:

class Template {

    // Set some defaults here if you want
    public $config = array(
        'item1'  =>  'default_value_1',
        'item2'  =>  'default_value_2',
    );
    // Or don't
    // public $config = array();

    // Set a NULL default value in case we want to use defaults
    public function __construct($params = NULL)
    {
        // Loop through params and override defaults
        if ($params)
        {
            foreach ($params as $key => $value)
            {
                $this->config[$key] = $value;
            }
        }
    }

    public function some_function()
    {
        //i need the above parameters here

        // Here you go
        echo $this->config['item1'];
    }

}
Run Code Online (Sandbox Code Playgroud)

这会变成array('item1' => 'value1', 'item2' => 'value2');你可以使用的东西$this->config['item1'].您只是将数组分配给类变量$config.如果您愿意,您还可以遍历变量并验证或更改它们.

如果您不想覆盖您设置的默认值,则不要在$params数组中设置该项.根据需要使用尽可能多的不同变量和值,这取决于你:)

正如Austin明智地建议的那样,请务必阅读php.net并亲自体验.文档可能会令人困惑,因为它们提供了大量边缘案例,但如果您查看Codeigniter中的库,则可以看到一些示例或如何使用类属性.它是真正的面包和黄油的东西,你必须熟悉到任何地方.