2

I've been looking at Magic Constants and Reflection in PHP to see if the following is possible:

function one() {

  setVars();

  // $node would be in scope
  print_r($node);

}

function setVars() {
  return $node = '2';
}

Is this a classical programming concept? Reflection seems to be the closest thing. Basically, I just want to define variables in a different scope (the scope/context of the function that called the setVars() function).

8
  • $node wouldnt be in scope there. you would have to do $node = setVars()... unless im missing something. Commented Apr 1, 2013 at 15:32
  • 1
    php.net/manual/en/functions.returning-values.php#example-158 Commented Apr 1, 2013 at 15:37
  • 2
    you could return an array and then use extract... or jsut use the variables in the array. Commented Apr 1, 2013 at 15:37
  • 2
    @prodigitalson or just use the list syntax like in the example I posted, which was made for this purpose. Commented Apr 1, 2013 at 15:38
  • 2
    @mavame I don't understand why one would do that. If you want to tightly couple two different functions like that, why not put them in a common class so that all the methods would have access to the class properties (which could be set with a method like setVars)? Commented Apr 1, 2013 at 15:40

2 Answers 2

1

For more than one variable try to store them in a array and return the array.

function one() {

  $nodeArray = setVars();
  print_r($nodeArray );

}

function setVars() {
  $nodeArray[] = 1;
  $nodeArray[] = 1;
  $nodeArray[] = 1;
  return $nodeArray;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I should have been more clear. I want to define MULTIPLE variables, not just one.
This is MULTIPLE dear. The difference is i stored the values in a array.
Except that your example returns only one value. I would then need to run extract on the result to have multiple local variables defined inside one(). Thanks for your answer
This one array can be splited easy by list().
1

Take a look at extract().

function one() {

  $vars = setVars();
  extract($vars);

  // $node1 would be in scope
  print_r($node1);

}

function setVars() {
  $node1 = '1';
  $node2 = '2';
  return compact('node1','node2');
}

It should be said, although this is possible, it often leads to terrible architecture and problems down the line.

2 Comments

There is no need to compact and extract I think.
No, probably not, but the question was asking about defining local variables in another scope, and I think this is the closest you get to that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.