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';
}
如何在另一个函数中获取此函数的值?
像:
function second() {
foreach($list as $item ) {
get ${'variable_' . $item->ID};
// getting identical value from first() function
}
get $ordinary_variable;
}
$variable_id
first()
(id为数字)
$list
是Array()
,可以有超过100个值。$ordinary_variable
是一个字符串。感谢。
答案 0 :(得分:5)
你可以让第一个函数返回一个数组:
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;
}
然后:
function second() {
$values = first();
foreach($list as $item ) {
$values['variable_' . $item->ID];
// getting identical value from first() function
}
$values['ordinary_variable'];
}
或将其作为参数传递:
second(first());
我会反对global
,因为这会引入副作用并使代码难以维护/调试。
答案 1 :(得分:0)
${'variable_' . $item->ID}
超出了范围。也许您应该创建一个全局数组并将它们存储在那里。
简化示例
$myvars = array();
function first() {
global $myvars;
...
$myvars['variable_' . $item->ID] = $item->title;
}
function second() {
global $myvars;
...
echo $myvars['variable_' . $item->ID];
}