加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如何在CodeIgniter中使用正确的面向对象的模型与构造函数

发布时间:2020-12-13 16:29:40 所属栏目:PHP教程 来源:网络整理
导读:现在我创建CodeIgniter模型的方式是(即没有构造函数,必须一直传递userID并限制在一个对象上): $this-load-model('User');$this-user-set_password($userID,$password); 但我想这样做: $this-load-model('User');$User = new User($userID);$User-set_passw
现在我创建CodeIgniter模型的方式是(即没有构造函数,必须一直传递userID并限制在一个对象上):
$this->load->model('User');
$this->user->set_password($userID,$password);

但我想这样做:

$this->load->model('User');
$User = new User($userID);
$User->set_password($password);

更新:也许只是一个用户模型是一个很差的例子.

例如,如果我有一个有各种项目的购物清单,我想以这种方式使用PHP:

$this->load->model('List');
$this->load->model('Item');

$List = new List();
$items[] = new Item($itemName1,$itemPrice1);
$items[] = new Item($itemName2,$itemPrice2);

$List->add_items($items);

以这种方式处理PHP OO,CodeIgniter感到基本上破裂了.有谁有任何解决方案仍然可以在每个模型中使用超级对象?

你可以像你通常那样做:
require_once(APPPATH.'models/User.php');
$User = new User($userID);

或者,您可以依靠表级模型返回记录级别的模型:

$this->load->model('users_model'); // users (plural) is the table-level model
$User = $this->users_model->get_user($userID);

同时,在users_model中

require_once(APPPATH.'models/User.php');

public function get_user($userID)
{
  // get a record from the db
  // map record to model
  // return model
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读