Welcome Guest, Not a member yet? Register   Sign In
custom library with parameters : problem
#1

(This post was last modified: 11-13-2015, 06:17 AM by casa.)

hello,
i want to use custom libray with parameters on its constuctor. I've a fatal error.

My libray class (in folder library)
PHP Code:
// class file named Example.php
defined('BASEPATH') OR exit('No direct script access allowed');
class 
Example   
    private $items

 
   
    public 
function __construct($args) {
 
       $this->items $args;
 
   }
 
   
    public 
function get($key) {
 
       if(is_array($this->items) && array_key_exists($key$this->items)) {
 
           return $this->items[$key];
 
       } else {
 
           return $this->items;
 
       }
 
   }


My test view page
PHP Code:
//view file :  my_view.php
$params = array('red''green');
$this->load->library('Example'$params);

// Fatal error: Call to a member function get() on a non-object
echo $this->example->get(0) ;  
// but if i do this
$e = new Example($params);
echo 
$e->get(0) ; // it works 
Can you help me please.
Thank you.
Reply
#2

You can do it like this:

PHP Code:
private $items;

public function 
__construct($params = array())
{
    
// Are any settings being passed manually?  If so, set them
    
$this->items is_array($params) ? $params : array();

    
log_message('Your Class Name''Your Class Initialized');


What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

Thanks, but it's not working too because i note that :
- if you load library in the view page, there is error
- if you load library in the controller and then use it in the view, that's working !!
PHP Code:
// controller file
public function method_controller() {
     
$args = array('green''blue');
     
$this->load->library('example'$args);
     
$this->load->view('my_view');

PHP Code:
// view file : my_view.php
     
echo $this->example->get(0); // works 
Perhaps, it's the only way to do that.
Reply
#4

That's because CI controllers have access to the CI Global Super Objects, views do not.

PHP Code:
private $CI;

public function 
__construct()
{
    
$this->CI =& get_instance();

 
       parent::__construct();

    
log_message('Your Class Name''Your Class Initialized');


What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#5

$this will only contain objects that are loaded before the view is loaded.
If you want to load classes in a view you must do it like this:

PHP Code:
$ci =& get_instance();
$ci->load->library('yourlibrary');
$ci->yourlibrary->get(); 

This is one of the reasons using $this in views should be avoided. Pass everything you need in your view via the data argument when loading a view
Reply
#6

@Martin and InsiteFx
Thank you for your help Smile and explaination
Reply




Theme © iAndrew 2016 - Forum software by © MyBB