开发者

Passing arguments when loading custom CodeIgniter library

I'm trying to implement a class I've written as CodeIgniter library.

Somehow I can't get CI's load() method to pass multiple arguments to the class's constructor function.

My class is designed to get 3 arguments, 2 arrays and one optional string.

The constructor looks somewhat like this:

public function __construct($array, $array,$string=""){
/** code **/
}

The relevant part from the controlle开发者_如何学Cr:

function index(){
  $array1 = array('key1'=>'value','key2'=>'value');
  $array2 = array('key1'=>'value','key2'=>'value');
  $string = "value";
  $params = array($array1,$array2,$string);
  $this->load->library("MyClass",$params);
}

Loading the controller generates this error :

Message: Missing argument 2 for MyClass::__construct()

This is really puzzling me. It seems the first argument gets sent fine and then it chokes on the second argument. Any clues on why this is happening will be greatly appreciated.


You need to modify your class constructor to handle the passed data as described here:

https://www.codeigniter.com/user_guide/general/creating_libraries.html

public function __construct($params)
{
    $array1 = $params[0];
    $array2 = $params[1];
    $string = $params[2];

    // Rest of the code
}


you forgot the $ on array2 when declaring params, causing it be passed as a constant that isn't defined instead of an array.


Passing Parameters When Initializing Your Class

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); If you use this feature you must set up your class constructor to expect data:

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

class Someclass {

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

?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜