Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Codeigniter can return a database query as generic "Object" like:

$q = $this->db->get("some_table");
$obj = $this->q->row();
$var = $obj->some_property

In my case I want to make a PHP class who's public variables are 1 for 1 with the database columns, along with some public methods. Is there a quick one-shot way to cast or convert the generic "Row" object into my custom class object? I've read posts that hint that it is certainly possible, but most involve a really hacky serialize/deserialize solution. In the past I have just done:

public function __construct($row) {
  $this->prop = $row->prop;
  $this->id = $row->id;
  $this->value = $row->value;
}

And I find this is very tedious and makes ugly code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
255 views
Welcome To Ask or Share your Answers For Others

1 Answer

See the third section under result():

CodeIgniter User Guide: Generating Query Results

You can also pass a string to result() which represents a class to instantiate for each result object (note: this class must be loaded)

$query = $this->db->query("SELECT * FROM users;");

foreach ($query->result('User') as $row)
{
    echo $row->name; // call attributes
    echo $row->reverse_name(); // or methods defined on the 'User' class
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...