V
V
VANY2018-02-13 23:49:22
PHP
VANY, 2018-02-13 23:49:22

Why doesn't calling array inside a function work?

Code example:

$obj = json_decode($content, true);

return $obj; //работает

function test() { return $obj; }
test(); // не работает

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

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Sanych, 2018-02-13
@mountpoint

The scope is not the same. Do it this way

function test() {
 global $obj;
 return $obj; 
}
test(); // заработает

A
Artem, 2018-02-14
@proudmore

Never use global, it's 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 case of lambda, you can use use like below.

$obj = json_decode($content, true);

return $obj; //работает

function test($obj) { return $obj; }
test(); //работает

function($obj){
    return $obj; //работает
}

function() use ($obj){
    return $obj; //работает
}

S
Stalker_RED, 2018-02-14
@Stalker_RED

A very similar question to which I just answered
Why is the php script ignoring the function?
In short, you seem to be used to how closures work in js. But in most other languages ​​it doesn't work that way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question