2

使用PDOStatement::bindParam(),可以将参数绑定到变量——这在多次执行准备好的语句时特别有用,每个语句都有不同的参数值。例如:

$dbh = new PDO('mysql:dbname=foo', 'eggyal', 'password1');
$qry = $dbh->prepare('DELETE FROM bar WHERE qux = ?');
$qry->bindParam(1, $qux, PDO::PARAM_INT);

while (true) {
  $qux = ... ;
  $qry->execute();
  // etc
}

我的问题是:

  1. 是否可以将参数绑定到对象的成员变量?例如:

    $qry->bindParam(1, $obj->qux, PDO::PARAM_INT);
    
  2. 如果是这样,这样的参数绑定到哪个 object的成员变量:bindParam()调用时引用的那个,还是语句执行时引用的那个?例如:

    $obj->qux = 123;
    
    $obj = new stdClass();
    $obj->qux = 456;
    
    $qry->execute();  // which value is used for qux ?
    
  3. 这种行为记录在哪里(如果有的话)?

4

1 回答 1

5

PHP 存储变量的引用以使用它。当您调用$qry->bindParam(1, $obj->qux, PDO::PARAM_INT)时,存储的引用是实例化类成员的引用。

When you change the member $obj->qux, the reference is still the same than the one stored in your $obj. However, if you reinstanciate $obj to a new class, then every references are changed, but your old object is still in memory ! So when you assign a new value to the new $obj->qux, it is not the same variable used, so running $qry->execute will use the old value.

I hope I've been clear enough.

于 2012-12-29T01:09:36.153 回答