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

Dacobah picture Dacobah · Dec 17, 2012 · Viewed 10.2k times · Source

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?

Answer

Oscar Broman picture Oscar Broman · Dec 17, 2012

CodeIgniter has built-in functionality for this!

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