我已经扩展了PHP的mysqli
类,它工作正常。但是,如何在查询时让它返回一个自定义结果对象(或者一个用于插入/更新/删除等的布尔值)?扩展mysqli_result
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对象,但我无法弄清楚如何返回非一个布尔值,选择基于查询:
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;
}
}
真,我试图避免这样做,虽然。 – Petah 2011-06-01 01:49:27
@Petah你仍然可以扩展'mysqli_result',但是如果没有先得到一个正常的结果然后再适应它,我就无法看到返回你的类。 – Phil 2011-06-01 01:55:12
那么你可以,如果你使用'$ this-> real_query($ query);返回新的MySQLiResult($ this);'但是不会为非基于选择的查询返回布尔值。 – Petah 2011-06-01 02:02:49