0

Hi I am new to php and I just run into a problem. I would like to get local variable data outside the function after it was called.

function MyFunction() {
    $x = set
}

if($x == "set"){
    code...
}
George
  • 1
  • 1
  • How are you calling `MyFunction()`? Perhaps it should *return* the `$x` value? Then you could set that value to a local variable where you need to use it. – David Jan 05 '19 at 11:57
  • Variables don't work like that. "local" means that they cease to exist when the function call ends. Just keep going in whatever tutorial you're following and this will eventually make sense to you. You will also find ways to achieve what you want without this particular (impossible) solution that you are trying. – Ulrich Eckhardt Jan 05 '19 at 11:58
  • Why not make the function return variable $x instead, by using the return statement. However, if you still need to access var $x from outside the function, then you need to call the function and also set the variable visibility scope to global like so: `function MyFunction() { global $x; $x = 'set'; } global $x; if ( 'set' == $x ) { // code }` – John Zenith Jan 05 '19 at 12:07

1 Answers1

0

You can't do that. Instead return the value from the function.

function MyFunction() {
    $x = "set";
    return $x
}

if(MyFunction() == "set"){
    code...
}
Nishant
  • 7,504
  • 1
  • 21
  • 34