Welcome Guest, Not a member yet? Register   Sign In
Easier access to objects ($this->object instead of $this->CI->object)
#1

[eluser]Unknown[/eluser]
If you want to access objects in CI libraries you need to do something like this:
Code:
class Some_class {

    protected $CI;

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

    function some_function()
    {
        // Access to loader class
        $this->CI->load->library('form_validation');

        // Access to form_validation class
        $this->CI->form_validation->run();
    }

}

But you can use $this->object instead of $this->CI->object.

Everything you need is to create a new library with following code and save it as ./application/libraries/Library.php.
Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Library {
    
    protected $CI;
    
    function initialize()
    {
        $this->CI =& get_instance();
    }
    
    function __get($key)
    {
        return $this->CI->$key;
    }
    
}


// END Library class

/* End of file Library.php */
/* Location: ./application/libraries/Library.php */

Then you need to autoload this new class.
Code:
$autoload['libraries'] = array('library', 'database', 'form_validation' .....);

Any class in which you want to use $this->object instead of $this->CI->object must extends library 'Library'. You need not to declare any constructor method anymore. So, the new code of the original class will be ...
Code:
class Some_class extends Library {

    function some_function()
    {
        // Access to loader class without $this->CI->
        $this->load->library('form_validation');

        // Access to form_validation class without $this->CI->
        $this->form_validation->run();
    }

}

I know... my english is really bad, but I hope, I helped you with writing more effective PHP code.

Thanks for reading ...


Messages In This Thread
Easier access to objects ($this->object instead of $this->CI->object) - by El Forum - 03-04-2012, 10:36 AM



Theme © iAndrew 2016 - Forum software by © MyBB