将codeigniter数据库结果对象转换为自定义对象 [英] Cast codeigniter database result object to custom object
问题描述
Codeigniter可以将数据库查询返回为通用的Object,如:
Codeigniter can return a database query as generic "Object" like:
$q = $this->db->get("some_table");
$obj = $this->q->row();
$var = $obj->some_property
在我的例子中,我想做一个PHP类的公共变量是1为1与数据库列,以及一些公共方法。有一个快速的一次性方法来转换或转换通用的行对象到我的自定义类对象吗?我已经阅读的帖子,暗示这是肯定可能的,但最涉及一个真正的hacky序列化/反序列化解决方案。在过去,我刚刚做了:
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.
推荐答案
查看 result()
下的第三部分:
您还可以将一个字符串传递给result(),它表示为每个结果对象实例化的类(注意:此类必须加载)
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
}
这篇关于将codeigniter数据库结果对象转换为自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!