在PHP中奇怪的数组创建? [英] Weird Array Creation in PHP?
问题描述
我读为mysqli_stmt_bind_result PHP手册看到在评论:
while ( $field = $meta->fetch_field() ) {
$parameters[] = &$row[$field->name];
}
因为既不$ PARAMS也不$行这一行,为什么/如何做这一行工作的?
given that neither $params nor $row existed before that line, why/how does that line work?
推荐答案
PHP实际上并没有变量的声明。这意味着,在某些情况下,你可以参考变量,而实际上不必事先他们宣布。我说的有些是因为:
PHP doesn't actually have variable declaration. That means in some cases you can reference variables without actually having them declared beforehand. I say some cases because:
foreach($undefinedArray as $key=>$value){
// will give a notice and a warning
// notice: undefined variable
// warning: invalid argument to foreach
}
但是,这并不意味着你不能做一些像这样:
But this doesn't mean you can't do something like so:
for($i=0;$i<5;$i++){
$undefinedArray[]=$i;
}
// will create an array with 5 indexes, each holding the numbers 0 through 4
这工作,因为 $ undefinedArray
找不到创造的飞行。
This works because $undefinedArray
is not found and created on the fly.
现在,关于你自己的情况。我会假设你的意思这个帖子。我不得不承认,这是一个非常有趣的解决方案,我要去尝试克制自己无法评论任何一种不好的做法的存在,但让我们坐上去解释它!
Now, regarding your own case. I'm gonna assume you mean this post. And I have to admit, that's a very interesting solution, I'm gonna try to restrain myself from commenting on any kind of bad practice there, but let's get on to explaining it!
$params[] = &$row[$field->name];
这是那里的奇迹发生,这实际上是由于与放大器;.因为&安培;!$行['unknown_index']
,实际的创建指数
This is where the magic happens and it's actually due to the &. Because &$row['unknown_index']
, actually creates the index!
这意味着,上述说法做两件事情。首先,它创建与 $行保存为索引中的每一列名的数组
( $行[$现场&GT;名称]
)。然后,它在 $ PARAMS
保存一个指针,每个元素从 $行
。
This means that above statement does 2 things. First it creates an array with each column name saved as an index in $row
($row[$field->name]
). Then it saves a pointer to each of the elements from $row
in $params
.
call_user_func_array(array($stmt, 'bind_result'), $params);
这确实 $ stmt-&GT; bind_result()
。但在 $ PARAMS
作为参数传递bind_result每个元素。而且因为他们是按引用传递,$行的各项指标将举行各自选定的领域。
This does $stmt->bind_result()
. But passes each of the elements in $params
as parameters to bind_result. And since they're passed by reference, each index of $row will hold each of the selected fields.
剩下的应该很容易,现在弄清楚。
The rest should be easy to figure out now.
如果你有任何问题。随意问!
If you got any questions. Feel free to ask!
这篇关于在PHP中奇怪的数组创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!