I'm currently working with the Codeigniter framemwork. In the code below, I would like to get an Animal_model object, not a stdClass Object.
<?php
class Animal_model extends CI_Model{
    var $idanimal;
    var $name;
    public static $table = 'animals';
    function __construct() {
        parent::__construct();
    }
    function getone(self $animal){
        $query = $this->db->get_where(self::$table, array('id_animal' => $animal->idanimal));
        if($query == FALSE){
            return FALSE;
        }else{
            return $query->row(); // How to get an Animal_model object here? 
        }
    }
}
$lion = new Animal_model();
$lion->idanimal = 25; 
var_dump($lion); // It says "object(Animal_model)".
$lion = $lion->getone($lion);
var_dump($lion); // Now it says "object(stdClass)".
?>
How to convert $query->row() to an Animal_model object?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With