문제

Using PDOStatement::bindParam(), one can bind a parameter to a variable—which is especially useful when a prepared statement is executed multiple times, each with different parameter values. For example:

$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
}

My questions are:

  1. Is it possible to bind a parameter to the member variable of an object? For example:

    $qry->bindParam(1, $obj->qux, PDO::PARAM_INT);
    
  2. If so, to which object's member variable is such a parameter bound: that which is referenced at the time of the bindParam() call, or that which is referenced upon statement execution? For example:

    $obj->qux = 123;
    
    $obj = new stdClass();
    $obj->qux = 456;
    
    $qry->execute();  // which value is used for qux ?
    
  3. Where is this behaviour documented (if at all)?

도움이 되었습니까?

해결책

PHP stores the reference of the variable to use it. When you call $qry->bindParam(1, $obj->qux, PDO::PARAM_INT), the reference stored is the reference of the member of the instanciated class.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top