在fetch_field中使用引用

时间:2013-08-29 11:39:08

标签: php reference

我有这个例子

 function read()
{
   $parameters = array();
   $results = array();

   $mysql = new mysqli('localhost', 'root', 'root', 'test') or die('There was a problem connecting to the database');
   $stmt = $mysql->prepare('SELECT id,body,posts FROM post') or die('Problem preparing query');
   $stmt->execute();

   $meta = $stmt->result_metadata(); 

   while ( $field = $meta->fetch_field() ) {

     $parameters[] = &$row[$field->name];

   }

   call_user_func_array(array($stmt, 'bind_result'), $parameters);

   while ( $stmt->fetch() ) {
      $x = array();

      foreach( $row as $key => $val ) {

         $x[$key] = $val;
      }
      $results[] = $x;
   }

   return $results;
}

$results = read();

我想知道为什么我需要在这个例子中引用$parameters[] = &$row[$field->name]; 没有& ,它无效。我在link中找到了这个例子。你能解释一下为什么需要使用引用和var $ row来自。它是fetch_field的一部分吗?

1 个答案:

答案 0 :(得分:0)

$parameters[] = &$row[$field->name];

表示$parameters[]现在引用$row[$field->name],即$parameters[]现在指向$row[$field->name]的值,这意味着$row[$field->name]中的任何更改也会反映在$parameters[]中{1}}

请参阅此示例以更好地完成任务!

<?php
$foo = 'Hello';
$bar = 'World'; 
print $foo . " " . $bar;// Hello World

$foo = &$bar;
$bar = 'Hello My World';

print $foo;// Hello My World
print $bar;// Hello My World

?>

希望这有帮助!