我有一个CodeIgniter模型:
<?php
class Person_model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function list_persons() {
$query = $this->db->get('persons');
return $query->result_array();
}
public function foobar() {
return 'Custom function here';
}
}
?>
Run Code Online (Sandbox Code Playgroud)
该功能list_persons()非常自我解释.它从persons数据库表中获取所有结果.
目前它返回数组列表中的结果,如下所示:
array(2) {
[0] => array(3) {
["id"] => string(1) "1"
["first_name"] => string(6) "Test 1"
}
[1] => array(3) {
["id"] => string(1) "2"
["first_name"] => string(6) "Test 2"
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以让函数list_persons()返回:
array(2) {
[0] => Person_model {
"id" => 1
"first_name" => "Test 1"
}
[1] => Person_model {
"id" => 2
"first_name" => "Test 2"
}
}
Run Code Online (Sandbox Code Playgroud)
这样我就可以使用我写的自定义函数Person_model,例如:
foreach($this->person_model->list_persons() as $person) {
echo $person->foobar();
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
list_person()像这样更新你的方法(使用$query->result()):
public function list_persons() {
$query = $this->db->get('persons');
return $query->result('Person_model');
}
Run Code Online (Sandbox Code Playgroud)