Welcome Guest, Not a member yet? Register   Sign In
[solved] doubts using CI super-object
#1

[eluser]jozeunico[/eluser]
Hello, well I have a couple of doubts about how to invoke this object let me show you :

I'm developing my own library (personal project) and I try to do this:

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

class Moo{

    var $CI = & get_instance();        ;
    
    var $nombre = 'allende';
    
    function __construct()
    {        
             echo $this->nombre;
    }
    
    function showRegisterForm()
    {    
        
        $this->CI->load->helper('moo_add');
        //echo var_dump($CI);
        return show_Register_Form();
    }
}

?>

I understood that to user CI helpers, libraries, etc I need to get an instance (by reference) of CI super object using & get_instance();
But what I don't get it is Why I can't do it like above ? I mean:

The library is a class then I try to set the CI super object as a property of the library but, it doesn't work (like the property "$nombre".

I know that I can instance CI super-object inside a method and it works ver well, but my doubt it's Why I need to do it in a method? like this (even I tried at the __construct method and it works):

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

class Moo{

    
    var $nombre = 'allende';
    
    function __construct()
    {        
        echo $this->nombre;
        $this->CI =& get_instance();        
    }
    
    function showRegisterForm()
    {    
        
        $this->CI->load->helper('moo_add');
        //echo var_dump($CI);
        return show_Register_Form();
    }
}

?>

Well any clue, link or information it'll be welcome, thanks everybody.
#2

[eluser]BrianDHall[/eluser]
I believe this is purely due to the fact that in PHP you can't execute a function simply in a class definition, such as for initialization of a variable. The proper place for such initialization is in the constructor - it's what it exists for.

So you declare the variable outside any function, then you initialize it in the constructor. It's just good OOP form, really.
#3

[eluser]InsiteFX[/eluser]
Hi,

BrianDHall is correct it needs to be done in the constructor.

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

class Moo{

    var $CI;
    
    var $nombre = 'allende';
    
    function __construct()
    {        
             $CI = & get_instance();
             echo $this->nombre;
    }
    
    function showRegisterForm()
    {    
        
        $this->CI->load->helper('moo_add');
        //echo var_dump($CI);
        return show_Register_Form();
    }
}

?>

Enjoy
InsiteFX
#4

[eluser]jozeunico[/eluser]
Thanks both of you, so If I got it I can not user funcionts to initialize properties in the definition class.

Well, I thinks that¨s all, thank you again.




Theme © iAndrew 2016 - Forum software by © MyBB