无法通过$ stmt-> bind_param的引用传递常量变量?

问题描述

| 这是我的代码段:
private function add_user_limit()
{
    global $MysqLi;
    $stmt = $MysqLi->prepare(\"INSERT INTO `user_limits` (user_ip,downloads_left) VALUES (?,?)\");
    $stmt->bind_param(\"si\",$this->user_ip,DEFAULT_USER_LIMIT);
    $stmt->execute();
    if($stmt->affected_rows == 0)
        throw new Exception(\"Couldn\'t add new user to the user_limits table\");
    $stmt->close();
    $this->downloads_left = DEFAULT_USER_LIMIT;
}
DEFAULT_USER_LIMIT
被定义为
8
,但是使用上面的代码,我得到此错误
Fatal error: Cannot pass parameter 3 by reference in C:\\xampp\\htdocs\\classes\\limits.class.PHP on line 38
但是,如果我这样做:
private function add_user_limit()
{
    global $MysqLi;
    $stmt = $MysqLi->prepare(\"INSERT INTO `user_limits` (user_ip,?)\");
    $user_limit = DEFAULT_USER_LIMIT; // For some reason we can\'t pass a constant to bind_param
    $stmt->bind_param(\"si\",$user_limit);
    $stmt->execute();
    if($stmt->affected_rows == 0)
        throw new Exception(\"Couldn\'t add new user to the user_limits table\");
    $stmt->close();
    $this->downloads_left = DEFAULT_USER_LIMIT;
}
有用。我只是想知道为什么会这样,因为这对我来说真的没有意义。我看不出为什么
bind_param()
不能将常量变量作为参数。 谢谢!     

解决方法

很简单,这是因为您不能通过引用传递常量,并且这样做是没有意义的,因为它是不可变的。顺便说一句,常量不是变量。它就在名称中。     ,可以通过引用传递以下内容: 变量,即foo($ a) 新语句,即foo(new foobar()) 从函数返回的引用 不得通过引用传递其他表达式,因为结果是不确定的 http://php.net/manual/zh/language.references.pass.php 另外, mysqli_stmt_bind_param()要求通过引用传递参数,而call_user_func_array()可以接受可以表示引用或值的变量列表作为参数。 http://php.net/manual/en/mysqli-stmt.bind-param.php     ,Mysqli的bind_param定义如下:
bind_param ( string $types,mixed &$var1 [,mixed &$... ] )
说明
&
表示变量是通过引用传递的,并且由于无法以这种方式引用PHP中的常量(例如
DEFAULT_USER_LIMIT
),因此只能将它们作为值传递,因为这就是它们的含义。 因此,如果您有一个强制通过引用传递的函数,则首先必须将常量的值存储到变量中,然后将变量传递(就像您所做的那样……) 现代解决方案-只需使用PDO 如果您可以使用PDO接口并且不需要通过引用传递值, 只需使用PDO的
bindValue()
+ PDO,在通常情况下,使用的方式与Mysqli几乎相同。
public bool PDOStatement::bindValue ( mixed $parameter,mixed $value [,int $data_type = PDO::PARAM_STR ] )
而且,如果您仍然需要通过引用传递,PDO也有一个
bindParam()
public bool PDOStatement::bindParam ( mixed $parameter,mixed &$variable [,int $data_type = PDO::PARAM_STR [,int $length [,mixed $driver_options ]]] )