How to get class object with $query->row on Codeigniter How to get class object with $query->row on Codeigniter codeigniter codeigniter

How to get class object with $query->row on Codeigniter


CodeIgniter has built-in functionality for this!

return $query->row(0, 'Animal_model');


    if($query == FALSE){        return FALSE;    }else{       // How to get an Animal_model object here?        $row = $query->row();       $animal = new Animal_model();       $animal->idanimal = $row->idanimal;       $animal->name= $row->name;       return $animal;    }

The above will do what you want but I don't think it's a very good idea. It would be better to have a second class such as Animal which doesn't extend any model that you can use to represent an animal.

class Animal{    public name = '';    public id = 0;    public function __construct($id, $name)    {        $this->id = $id;        $this->name = $name;    }}

In your model, you can create instances of this and return them, instead of returning model objects.

    if($query == FALSE){        return FALSE;    }else{        $row = $query->row();        return new Animal($row->idanimal, $row->name);    }

I would also change the getone function to take an ID instead, and select where this ID matches:

function getone($id){

This way you use the model as a manager for the animals, the model deals with the data and returns Animal objects.


Instead of return $query->row(); you can instantiate an object of the Animal_model class and assign the values from $query->row() to the properties of the object. But I'm not sure I see any value in doing this. You will still be getting the same data back. Is there a method you need in the Animal_Model class that you want to call after retrieving the row?

Sidebar note... You might want to avoid the use of "var" to describe your properties. Probably you want to use "Protected" unless you can think of a reason for Public or Private.