Example code:
$obj=json_decode($content, true);

return $obj;//works

function test() {return $obj;}
test();//does not work

* the output method does not matter, the function for some reason does not contain anything

3 Answers 3

The scope is not the same.Do this

function test() {
 global $obj;
 return $obj;
}
test();//earns
A very similar question that I just answered

Why does the php script ignore the function?

In short: it looks like you are used to how closures work in js.But in most other languages ​​it doesn't work that way.
  • Now everyone on zhabaskriptah sit and do not understand what is happening – Irish Android Feb 14 '18 at 00:22
Never use global, this is evil, leading to the very bottom.
In order for a function to have access to some variables, you need to pass these objects, or references to them, as an argument to the function.
In the case of lambda, you can use use, as shown below.

$obj=json_decode($content, true);

return $obj;//works

function test($obj) {return $obj;}
test();//works

function($obj) {
    return $obj;//works
}

function() use($obj) {
    return $obj;//works
}
  • function test ($obj) {return $obj;}
    test();//works

    test ($obj)

    is the evil leading at the very bottom

    still goto is. so there is another knock on the bottom
    – Cute Chinchilla Feb 14 '18 at 09:43