gpt4 book ai didi

PHP mysqli 包装器 : passing by reference with __call() and call_user_func_array()

转载 作者:行者123 更新时间:2023-12-04 06:56:01 25 4
gpt4 key购买 nike

我是 stackoverflow 的长期粉丝,第一次发帖。我很想看看是否有人可以帮助我解决这个问题。让我用一些代码深入研究,然后我会解释我的问题。我有以下包装类:

class mysqli_wrapper
{
private static $mysqli_obj;
function __construct() // Recycles the mysqli object
{
if (!isset(self::$mysqli_obj))
{
self::$mysqli_obj = new mysqli(MYSQL_SERVER, MYSQL_USER, MYSQL_PASS, MYSQL_DBNAME);
}
}
function __call($method, $args)
{
return call_user_func_array(array(self::$mysqli_obj, $method), $args);
}
function __get($para)
{
return self::$mysqli_obj->$para;
}
function prepare($query) // Overloaded, returns statement wrapper
{
return new mysqli_stmt_wrapper(self::$mysqli_obj, $query);
}
}

class mysqli_stmt_wrapper
{
private $stmt_obj;
function __construct($link, $query)
{
$this->stmt_obj = mysqli_prepare($link, $query);
}
function __call($method, $args)
{
return call_user_func_array(array($this->stmt_obj, $method), $args);
}
function __get($para)
{
return $this->stmt_obj->$para;
}
// Other methods will be added here
}

我的问题是当我调用 bind_result()mysqli_stmt_wrapper类,我的变量似乎没有通过引用传递,也没有返回任何内容。为了说明,如果我运行这部分代码,我只会得到 NULL:
$mysqli = new mysqli_wrapper;

$stmt = $mysqli->prepare("SELECT cfg_key, cfg_value FROM config");
$stmt->execute();
$stmt->bind_result($cfg_key, $cfg_value);

while ($stmt->fetch())
{
var_dump($cfg_key);
var_dump($cfg_value);
}
$stmt->close();

我还从 PHP 中得到一个很好的错误,它告诉我: PHP Warning: Parameter 1 to mysqli_stmt::bind_result() expected to be a reference, value given in test.php on line 48
我试图重载 bind_param()函数,但我不知道如何通过引用获取可变数量的参数。 func_get_args()似乎也帮不上忙。

如果我通过引用传递变量,如 $stmt->bind_result(&$cfg_key, &$cfg_value)它应该可以工作,但这是不推荐使用的行为并且会引发更多错误。

有人对此有一些想法吗?非常感谢您的宝贵时间。

最佳答案

如果您从 mysqli_stmt 类扩展,您将绕过引用问题。 (没有干净的解决方案)

class mysqli_stmt_wrapper extends mysqli_stmt {
public function __construct($link, $query) {
parent::__construct($link, $query);
}
}

class mysqli_wrapper extends mysqli {
public function prepare($query) {
return new mysqli_stmt_wrapper($this, $query);
}
}

关于PHP mysqli 包装器 : passing by reference with __call() and call_user_func_array(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2566289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com