0

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.

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.