How Do You Create Multiple Instances of a Library

2020-06-20 12:42发布

问题:

I'd like to create several instances of a class in CodeIgniter. I have created my class as a library, but cannot figure out the syntax to use to create more than one instance.

回答1:

From the CodeIgniter users guide:

CI Users Guide: Loader Class

Assigning a Library to a different object name

If the third (optional) parameter is blank, the library will usually be assigned to an object with the same name as the library. For example, if the library is named Session, it will be assigned to a variable named $this->session.

If you prefer to set your own class names you can pass its value to the third parameter: $this->load->library('session', '', 'my_session');

// Session class is now accessed using:

$this->my_session

I think that's what you're looking for.



回答2:

I know this tread is long passed, but it was one of the questions I came across while looking for my answer. So here's my solution...

It's PHP. Create your class as a library, load it using the standard CI Loader Class, but use it like you would in a regular PHP script.

Build your class:

class My_class {

    var $number;

    public function __construct($given_number){
        $number = $given_number;
    }

    public function set_new_num($given_number){
        $number = $given_number;
    }
}

Load it:

// This will load the code so PHP can create an instance of the class
$this->load->library('My_class');

Then instantiate and use the object where needed:

$num = new My_class(24);

echo $num->number;
// OUTPUT: 24

$num->set_new_num(12);

echo $num->number;
// OUTPUT: 12

The only time I use $this->my_class is to make calls to static functions that I code.



回答3:

Sorry for reviving this topic but I think i might have something reasonable to add.

You can do this to add multiple instances of a class. I don't know if it violates codeigniter standard usage anyhow but seems more codeigniter-ish than loading a library (which creates $this->library_name which isn't used) and then making 2 MORE instances with "new" keyword.

$this->load->library( 'my_library', '', 'instance1' );
$this->load->library( 'my_library', '', 'instance2' );

$this->instance1->my_class_variable = 1; 
$this->instance2->my_class_variable = 2; 

echo $this->instance1->my_class_variable; // outputs 1
echo $this->instance2->my_class_variable; // outputs 2

I use this in my code to generate different menus. I have a "menu" class and different instances for each menu, with different menu items in each.