Return array of model objects instead of array of arrays in CodeIgniter 3

Viewed 1805

I have a CodeIgniter model:

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

The function list_persons() is quite self-explained. It fetches all results from persons database table.

Currently it returns results in a list of arrays, like this:

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"
  }
}

Is it possible to let the function list_persons() to return:

array(2) {
  [0] => Person_model {
    "id" => 1
    "first_name" => "Test 1"
  }
  [1] => Person_model {
    "id" => 2
    "first_name" => "Test 2"
  }
}

so that I can use the custom functions I wrote in the Person_model, such as:

foreach($this->person_model->list_persons() as $person) {
    echo $person->foobar();
}

Thanks in advance.

1 Answers
Related