CodeIgniter:在库加载时激活的类构造函数?

时间:2015-12-18 12:52:09

标签: php codeigniter

当我在CI控制器中加载库时,即使我还没有创建对象,也会自动激活类构造函数。

这很奇怪。可以通过配置或其他东西修复吗?在网上找不到任何东西。

我的控制器:

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');
    }
}

我的班级:

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

class Users {

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

        public function some_method() {

        }
}

代码将两次输出“Hello World”。

2 个答案:

答案 0 :(得分:2)

$this->load->library('myLib');设置图书馆,因此您无需使用new关键字。

$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

答案 1 :(得分:0)

在Codeigniter中,当您调用库或调用帮助程序或调用控制器或模型或其中的任何内容时,只需等同于新的关键字。

我的意思是如果你想创建一个新的用户对象,你只需要执行以下操作。 只需将第一个用户的实例存储在可变的中。

//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