Hellsdev
Hellsdev

Reputation: 3

CodeIgniter: Class constructer activated on library load?

When I load a library in CI controller the class constructor is activated automatically, even if I didn't create an object just yet.

This is weird. can this be fixed via config or something? didn't find anything on the web.

My Controller:

defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $this->load->library('users',false);
        $user = new Users();
        $this->load->model('welcome_model');
        $this->load->view('welcome_message');
    }
}

My Class:

defined('BASEPATH') OR exit('No direct script access allowed');

class Users {

        public function __construct($uname, $fname, $lname) {
            print "Hello World!";
        }

        public function some_method() {

        }
}

The code will output "Hello World" twice.

Upvotes: 0

Views: 119

Answers (2)

Alaa M. Jaddou
Alaa M. Jaddou

Reputation: 1189

in Codeigniter when you call library or call helper or call a controller or a model or anything of these its just equivalent to the new key word.

i mean if you want to make a new object of user you just do the following. just store the instance of your first user in a varaible.

//creating first instance
$user = $this->load->library('users', $first_user_parameters);
//creating second instance
$user2 = $this->load->library('users', $second_user_parameters);

// $this->load->library('users', $param) === $user = new User($param);
in codeigniter they convert the load to new keyword by the ci_loader

Upvotes: 0

JC Sama
JC Sama

Reputation: 2204

$this->load->library('myLib'); instanciate the library, so you don't need to use the new keyword.

$params_for_the_constructor = array(
   'id' => 1, 
   'firstname' => 'Jemmy', 
   'lastname' => 'Neutron'
);
$this->load->library('users', $params_for_the_constructor);
$this->users->some_method();


class Users {

  private $id;
  private $firstname;
  private $lastname;

  public function __construct(array $params = array()) {

    if (count($params) > 0) {
      $this->initialize($params);
    }
    log_message('debug', "Users Class Initialized");
  }

  public function some_method() {

  }

  public function initialize(array $params = array()) {
    if (count($params) > 0) {
      foreach($params as $key => $val) {
        if (isset($this->{$key}))
          $this->{$key} = $val;
      }
    }
    return $this;
  }
}

https://ellislab.com/codeigniter/user-guide/general/creating_libraries.html

Upvotes: 2

Related Questions