在PHP中使用函数内部的全局变量 [英] Making global var from inside a function in PHP
问题描述
是可能的?
谢谢。
编辑
好的,这就是我所建的。这是危险的吗?
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'$' $ value){
global $$ key;
$$ key = $ value;
}
}
然后我试着让我的生活更轻松如下所示:
$ result = mysql_query(SELECT first_name,last_name,address FROM users ORDER BY id ASC);
while($ row = mysql_fetch_array($ result)){
extract_values($ row);
#[用变量做一些事情。]#
}
I我正在努力节省时间。而不是为每一列创建自己的变量,如
$ first_name = $ row ['first_name'];
这个函数为我做了。
我不明白为什么在这种情况下它可能是危险的..
或作为usuall,我缺少的东西..
试试这个:
函数doSomething(){
global $ x;
$ x = 5;
$ / code>
如果你喜欢保存几个字节,你可以使用 $ _ GLOBALS
数组:
$ _ GLOBALS ['x'] = 5 ;
I am trying to define dynamically variables. I am using a function for this, but I don't know how to define the new var as global (because it never created before the function).
is that possible ?
Thanks.
edit
ok, this is what I've built. is it that dangerous ?
function extract_values($row) {
foreach ($row as $key => $value){
global $$key;
$$key = $value;
}
}
and then I'm trying to make my life easier like that:
$result = mysql_query("SELECT first_name, last_name, address FROM users ORDER BY id ASC");
while ($row = mysql_fetch_array($result)){
extract_values($row);
#[do some stuff with the variables.]#
}
I am doing it to save time. instead of creating for each column it's own variable like
$first_name = $row['first_name'];
This function does that for me. I don't see why in this case it might be dangerous.. or as usuall, i am missing something..
Try this:
function doSomething() {
global $x;
$x = 5;
}
If you prefer to save a couple of bytes, you can use the $_GLOBALS
array for this:
$_GLOBALS['x'] = 5;
这篇关于在PHP中使用函数内部的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!