phpcodeigniter

Load library by passing parameter to constructor in codeigniter


I am using codeigniter. I defined a library in code-igniter and is expecting a parameter in its constructor.This is my library code -

################# [My Library Code Test_lib.php ] ########################
<?php
class Test_lib
{
var $params;
public function __construct($params)
{
    $this->params = $params;
    echo $this->params;
}
}

In codeigniter documentation, it is mentioned that you can pass the parameter in the second argument. So,I am initializing it from controller as below -

<?php
class Test_cont extends CI_Controller {
function __construct()
{
    parent::__construct();
}

function test()
{
    $params = "abc";
    $this->load->library("test_lib",$params);
}
}   

I am getting following error -

A PHP Error was encountered Severity: Warning Message: Missing argument.....

Please assist.


Solution

  • $params must be an array. From the documentation:

    In the library loading function you can dynamically pass data as an array via the second parameter and it will be passed to your class constructor:

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

    In your case, you want to do something like this:

    function test()
    {
        $params[] = "abc"; // $params is an array
        $this->load->library("test_lib",$params);
    }