S
S
Shimpanze2020-05-26 10:32:53
PHP
Shimpanze, 2020-05-26 10:32:53

How to pass an external variable to a nested function?

Hello!

Example:

$myvar = 'abc';

function a() {
  global $myvar;
  var_dump( $myvar );
  // вывод: string(3) "abc" // переменная видна

  // теперь вложенная функция
  function b() {
    global $myvar;
    var_dump( $myvar );
  // вывод: // переменная не видна
  }
}


Why doesn't the nested function b()see the variable $myvar? And how to make her see this variable?

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2020-05-26
@Shimpanze

Because it is necessary to forget about volzhennye functions as about a terrible dream.
As well as about global variables.
Function parameters are used to pass a variable to a function.

function a($myvar) {
  var_dump( $myvar );
}
function b($myvar) {
    var_dump( $myvar );
}

simple, reliable, and you will not be strangled with a pillow at night by a person who, after you, will support these multi-storey layers of guano

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question