James
James

Reputation: 43627

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;
}

Thanks.

Upvotes: 2

Views: 21747

Answers (2)

Fosco
Fosco

Reputation: 38516

${'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];
}

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816364

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.

Upvotes: 6

Related Questions