N
N
newaitix2018-02-08 23:28:27
PHP
newaitix, 2018-02-08 23:28:27

How to get a variable inside a function?

$a=22;
function test(){
return $a;
}
echo test();

Why doesn't it work? Why is variable a not available inside the function ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2018-02-08
@newaitix

Scope as if
global $a write down

O
Oleg, 2018-02-09
@402d

As far as I understand, you wrote before in JavaScript.
https://medium.com/devschacht/glossary-of-modern-j...
pay attention to the concepts of
Cleanliness, Condition
So in PHP, and especially after the appearance of OOP in it , the
use of global is a bad form.
This is the fundamental difference between PHP and JS.
With each request, the script execution starts from scratch, i.e. without special measures,
the script does not know what the user has done before.

V
Vadim, 2018-02-09
@vadimek

I would do so

$a = 22;
$test = function () use ($a) {
return $a;
};
echo $test();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question