Passing parameters when initializing the library in Codeigniter

I am really new to Codeigniter and just studied from scratch. CI docs say:

$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 a simple example of how to transfer data from a controller to an external library using an array as parameters? I would like to see a simple example.

+4
source share
2 answers

All the designers of the Codeigniter library expect one argument: an array of parameters, which is usually passed when the class is loaded with the CI loader, as in your example:

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

I assume you are confused about the "Do something with $ params" part. You do not need to pass any parameters, but if you do, you can use them as follows:

 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 reinitialize later if you need:

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

One more note: if you have a configuration file that matches the name of your class, this configuration will load automatically. For example, if you have a file application/config/someclass.php :

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

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

+6
source

In the library directory, create one file Someclass_lib.php

Here is your library code

 if (!defined('BASEPATH')) exit('No direct script access allowed'); class Someclass_lib { public $type = ''; public $color = ''; function Someclass_lib($params) { $this->CI =& get_instance(); $this->type = $params['type']; $this->color = $params['color']; } } 

Use this code if you want to download the library

 $params = array('type' => 'large', 'color' => 'red'); $this->load->library('Someclass_lib', $params); 
+1
source

Source: https://habr.com/ru/post/1440512/


All Articles