問題描述
我擴展了 PHP 的 mysqli
類,效果很好.但是如何讓它在查詢時返回自定義結果對象(或用于插入/更新/刪除等的布爾值)?
I have extended PHP's mysqli
class, which works fine. But how can I make it return a custom result object (or a boolean for insert/update/delete etc) when querying?
namespace MyApp;
class MySQLi extends mysqli {
public function query($query, $resultmode = null) {
// This needs to return a MySQLiResult or a boolean
}
}
class MySQLiResult extends mysqli_result {
}
這樣做我可以返回一個 MySQLiResult 對象,但我無法弄清楚如何為非基于選擇的查詢返回一個布爾值:
Doing this I can return a MySQLiResult object, but I can't figure out how to return a boolean for non select based queries:
public function query($query, $resultmode = null) {
$this->real_query($query);
return new MySQLiResult($this);
}
更新:
這是我最終使用的:
class MySQLi extends mysqli {
public function query($query, $resultmode = null) {
$result = parent::query($query, $resultmode);
return is_bool($result) ? $result : new MySQLiResult($result);
}
}
class MySQLiResult {
private $result;
public function __construct(mysqli_result $result) {
$this->result = $result;
}
public function __call($name, $arguments) {
return call_user_func_array(array($this->result, $name), $arguments);
}
public function __set($name, $value) {
$this->result->$name = $value;
}
public function __get($name) {
return $this->result->$name;
}
}
推薦答案
可能最簡單的做法是將 MySQLiResult
類視為 mysqli_result
的裝飾器.例如
Probably the simplest thing to do would be treat your MySQLiResult
class as a decorator for mysqli_result
. For example
class MySQLiResult
{
private $result;
public function __construct(mysqli_result $result)
{
$this->result = $result;
}
}
然后,您可以將方法調用代理到內部結果并在需要時進行裝飾(添加功能).
You could then proxy method calls to the internal result and decorate (add functionality) where required.
這篇關于擴展 mysqli_result的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!