PHP从函数中获取变量 [英] PHP get variable from function
本文介绍了PHP从函数中获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function first(){
foreach($ list as $ item){
$ {'variable_'。 $ item-> ID} = $ item-> title;
//给出$ varible_10 ='一些文字'; (10可以用任何数字代替)
}
$ ordinary_variable ='something';
}
如何在另一个函数中获取此函数的值?
$ p $ function second(){
foreach($ list作为$ item){
获得$ {'variable_'。 $本期特价货品> ID};
//从first()函数获得相同的值
}
get $ ordinary_variable;
}
- 我们知道
code>
-
中已经存在$ variable_id
$ list 是一个Array()
,它可以有超过100个值。
- <$ c
$ b $ p
$ p
您可以让第一个函数返回一个数组:
$ values = array();
foreach($ list为$ item){
$ values ['variable_'。 $ item-> ID] = $ item-> title;
//给出$ varible_10 ='一些文字'; (10可以用任何数字代替)
}
$ values ['ordinary_variable'] ='东西';
返回$值;
}
然后:
function second(){
$ values = first();
foreach($ list为$ item){
$ values ['variable_'。 $本期特价货品> ID];
//从first()函数获得相同的值
}
$ values ['ordinary_variable'];
}
或将其作为参数传递:
second(first());
我反对
全局
,因为这会引入副作用并使代码难以维护/调试。function first() { foreach($list as $item ) { ${'variable_' . $item->ID} = $item->title; // gives $varible_10 = 'some text'; (10 can be replaced with any number) } $ordinary_variable = 'something'; }
How to get values of this function inside an another function?
Like:
function second() { foreach($list as $item ) { get ${'variable_' . $item->ID}; // getting identical value from first() function } get $ordinary_variable; }
- We know that
$variable_id
(id is numeric) already exists infirst()
$list
is anArray()
, which can have more than 100 values.$ordinary_variable
is a string.
Thanks.
解决方案You could let the first function return an array:
function first() { $values = array(); foreach($list as $item ) { $values['variable_' . $item->ID] = $item->title; // gives $varible_10 = 'some text'; (10 can be replaced with any number) } $values['ordinary_variable'] = 'something'; return $values; }
and then:
function second() { $values = first(); foreach($list as $item ) { $values['variable_' . $item->ID]; // getting identical value from first() function } $values['ordinary_variable']; }
or pass it as parameter:
second(first());
I would advice against
global
as this introduces side-effects and makes the code harder to maintain/debug.这篇关于PHP从函数中获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- <$ c
查看全文