Reputation: 976
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.
Upvotes: 18
Views: 40704
Reputation: 541
Load custom library
class custom_library
{
public $CI, $user_data = array();
private $_user_id = 0;
public function __construct(){
$this->CI = & get_instance();
$this->user_id = $this->CI->user_data['user_id'];
}
function test(){
echo $this->user_id;
}
}
$this->load->library('custom_library');
$this->custom_library->user_data = $this->user_data;
Upvotes: 0
Reputation: 3348
Class Test_lib
################# [My Library Code Test_lib.php ] ########################
<?php
class Test_lib {
var $parameter1;
var $parameter2;
var $parameter3;
public function __construct($parameters) {
/* array assoc */
$this->parameter1 = $parameters['argument1'];
$this->parameter2 = $parameters['argument2'];
$this->parameter3 = $parameters['argument3'];
/* object */
$oParameters = (object) $parameters;
$this->parameter1 = $oParameters->argument1;
$this->parameter2 = $oParameters->argument2;
$this->parameter3 = $oParameters->argument3;
}
}
Class Controller
<?php
class Test_cont extends CI_Controller {
function __construct() {
parent::__construct();
}
function test() {
$data = array( // array assoc
'argument1' => 'String 1',
'argument2' => 'String 2',
'argument3' => 'String 3'
);
$this->load->library("Test_lib", $data);
return $this->Test_lib->parameter1;
}
echo $this->test(); // String 1
}
Upvotes: 7
Reputation: 21565
$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);
}
Upvotes: 31
Reputation: 8461
You just need to modify the $params from a variable to array. hope this will work
function test()
{
$params = array(1=>'abc');
$this->load->library('test_lib',$params);
}
Upvotes: 6