Jam*_*mes 1 php variables function
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';
}
Run Code Online (Sandbox Code Playgroud)
如何在另一个函数中获取此函数的值?
喜欢:
function second() {
foreach($list as $item ) {
get ${'variable_' . $item->ID};
// getting identical value from first() function
}
get $ordinary_variable;
}
Run Code Online (Sandbox Code Playgroud)
$variable_id(id是数字)已经存在于first()$list是一个Array(),可以有超过100个值.$ordinary_variable 是一个字符串.谢谢.
你可以让第一个函数返回一个数组:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后:
function second() {
$values = first();
foreach($list as $item ) {
$values['variable_' . $item->ID];
// getting identical value from first() function
}
$values['ordinary_variable'];
}
Run Code Online (Sandbox Code Playgroud)
或将其作为参数传递:
second(first());
Run Code Online (Sandbox Code Playgroud)
我建议反对,global因为这会引入副作用并使代码更难维护/调试.