bind_result()和fetch()如何能够更改范围之外的变量?

时间:2014-11-14 19:53:45

标签: php oop mysqli

根据这个http://php.net/manual/en/language.variables.scope.php,bind_result不能改变我的变量。

$query = 'SELECT username, status FROM table WHERE id = ?';
$id = 5;

$stmt = $mysqli->prepare($query);

$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($username, $status);
$stmt->fetch();

// Now I can use $username and $status

echo "$username has the status of $status";

为什么这样可能,这是如何工作的,我怎么能在我自己的php类/方法中做到这一点?

2 个答案:

答案 0 :(得分:4)

它使用references

以下是一个例子:

// Notice the '&' on the 2nd param
// This is being passed in as a reference
function addToVal($val, &$ref){
    // If we edit '$ref', we are are editing the
    // variable being "referenced"
    $ref += $val;
}

那么,如果我们这样做:

$abc = 3;
addToVal(5, $abc);
echo $abc; // 8

$abc正由addToVal更新,因为它是通过引用传递的。

请注意bind_resulthttp://php.net/manual/en/mysqli-stmt.bind-result.php

的文档
  

bool mysqli_stmt :: bind_result(mixed& $ var1 [,mixed& $ ...])

它说&$var1,这是一个参考。

答案 1 :(得分:1)

通过参考 - !

function setMagically(&$ref){ 

    $ref = "Whatever value"; 

}


setMagically($someVar); 
echo $someVar;