PHP get variable from function
1 2 3 4 5 6 7 | 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'; } |
如何在另一个函数中获取该函数的值?
像:
1 2 3 4 5 6 7 | function second() { foreach($list as $item ) { get ${'variable_' . $item->ID}; // getting identical value from first() function } get $ordinary_variable; } |
- 我们知道
$variable_id (id是数字)已经存在于first() 中。 $list 是一个Array() ,可以有100多个值。$ordinary_variable 是一个字符串。
谢谢。
您可以让第一个函数返回一个数组:
1 2 3 4 5 6 7 8 9 | 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; } |
然后:
1 2 3 4 5 6 7 8 | function second() { $values = first(); foreach($list as $item ) { $values['variable_' . $item->ID]; // getting identical value from first() function } $values['ordinary_variable']; } |
或将其作为参数传递:
1 | second(first()); |
我建议不要使用
简化示例
1 2 3 4 5 6 7 8 9 10 11 12 13 | $myvars = array(); function first() { global $myvars; ... $myvars['variable_' . $item->ID] = $item->title; } function second() { global $myvars; ... echo $myvars['variable_' . $item->ID]; } |