当我在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”。
答案 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)
我的意思是如果你想创建一个新的用户对象,你只需要执行以下操作。 只需将第一个用户的实例存储在可变的中。
//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