开发者

PHP get variable from 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';
}

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 in 开发者_高级运维first()
  • $list is an Array(), 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.


${'variable_' . $item->ID} is out of scope. Perhaps you should create a global array and store them there.

simplified example

$myvars = array();

function first() {
  global $myvars;
  ...
  $myvars['variable_' . $item->ID] = $item->title;
}

function second() {
  global $myvars;
  ...
  echo $myvars['variable_' . $item->ID];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜