Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters when initializing a library in Codeigniter

Tags:

codeigniter

I am really new to Codeigniter, and just learning from scratch. In the CI docs it says:

$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass', $params);
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Someclass {

    public function __construct($params)
    {
        // Do something with $params
    }
}

Can you give me simple example how to pass data from controller to external library using array as parameters? I'd like to see a simple example.

like image 717
user642721 Avatar asked Feb 18 '23 19:02

user642721


1 Answers

All Codeigniter "library" constructors expect a single argument: an array of parameters, which are usually passed while loading the class with CI's loader, as in your example:

$params = array('type' => 'large', 'color' => 'red');
$this->load->library('Someclass', $params);

I'm guessing you're confused about the "Do something with $params" part. It's not necessary to pass in any params, but if you do you might use them like this:

class Someclass {
    public $color = 'blue'; //default color
    public $size = 'small'; //default size
    public function __construct($params)
    {
        foreach ($params as $property => $value)
        {
            $this->$property = $value;
        }
        // Size is now "large", color is "red"
    }
}

You can always re-initialize later like so, if you need to:

$this->load->library('Someclass');
$this->Someclass->__construct($params);

Another thing to note is that if you have a config file that matches the name of your class, that configuration will be loaded automatically. So for example, if you have the file application/config/someclass.php:

$config['size'] = 'medium';
$config['color'] = 'green';
// etc.

This config will be automatically passed to the class constructor of "someclass" when it is loaded.

like image 145
Wesley Murch Avatar answered May 19 '23 23:05

Wesley Murch