【问题标题】:How is bind_result() and fetch() able to change variables outside the scope?bind_result() 和 fetch() 如何能够改变范围之外的变量?
【发布时间】:2014-11-14 19:53:44
【问题描述】:

据此http://php.net/manual/en/language.variables.scope.phpbind_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 类/方法中做到这一点?

【问题讨论】:

    标签: php oop mysqli


    【解决方案1】:

    它使用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_result (http://php.net/manual/en/mysqli-stmt.bind-result.php) 的文档

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

    上面写着&$var1,这是一个参考。

    【讨论】:

      【解决方案2】:

      通过引用 -!

      function setMagically(&$ref){ 
      
          $ref = "Whatever value"; 
      
      }
      
      
      setMagically($someVar); 
      echo $someVar;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-03
        • 2016-01-05
        • 2021-12-05
        相关资源
        最近更新 更多