Welcome Guest, Not a member yet? Register   Sign In
Constructor Problem
#1

[eluser]marty123[/eluser]
Hi, I'm trying to implement my own library, there is an constructor like this one:
Code:
class Menu {
    
    function Menu()
    {
        $CI =& get_instance();  


    }

fucntion get_menu ($param){

$CI ->load->model('m_menu');
};
function three(){
...
}

But when I try to use $CI in functions, there is an error :


A PHP Error was encountered

Severity: Notice

Message: Undefined variable: CI

Filename: libraries/menu.php

Line Number: 29

I call my library this way:
Code:
$this->load->library('menu');
$menu1 = new Menu();
$error['menu'] = $menu1->get_menu('PL');
the solution is to add $CI =& get_instance();
in all functions in the class, but I thought it should take $CI from constructor, am I wrong?
#2

[eluser]Dam1an[/eluser]
For a start, you mis spelt function for get_menu
You need to either make the CI instance a class variable, or create an instance for each function

For the first method, use
Code:
class Menu {
    var $CI;
    
    function Menu() {
        $this->CI =& get_instance();
    }
    
    function get_menu($param) {
        $this->CI->load->model('m_menu');
        ...
    }
}
#3

[eluser]marty123[/eluser]
Thanks, that works.
I'm confused that in userguide is:

Once you've assigned the object to a variable, you'll use that variable instead of $this:

and example
Code:
$CI =& get_instance();

$CI->load->helper('url');
$CI->load->library('session');
$CI->config->item('base_url');
etc.
I'll do it Your way :coolsmile: , I think it's more comfortable and useful
Thanks again
#4

[eluser]Dam1an[/eluser]
I'm assuming that's only specific to that function
It's just trying to make the point that in most cases (eg controllers you use $this->load etc) but in this case you need to use $CI->load etc

If you make the CI instance a class variable, you access it just like any other class variable, ie. $this->CI
so it now becoes $this->CI->load etc

Clear things up a bit?
#5

[eluser]marty123[/eluser]
yeah, it's clear, thanks




Theme © iAndrew 2016 - Forum software by © MyBB