-1

This gives no error:

$c = function() {
    return 'xx';
};


echo $c();

And with the code below I get an error. Why?

Warning: Undefined variable $a

$a = function($v) {
    return $v;
};

$b = function($v) {
    return $a($v);
};

echo $b('something');
smolo
  • 737
  • 1
  • 15
  • 27
  • 3
    See [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Guy Incognito Mar 05 '23 at 08:18
  • I run the second code here and get that error: https://onlinephp.io/ – smolo Mar 05 '23 at 08:22

1 Answers1

0

The error "Warning: Undefined variable $a" is because the variable $a is defined inside the anonymous function assigned to $a, and it is not in the scope of the anonymous function assigned to $b.

In other words, the variable $a is not defined in the global scope, so when the function assigned to $b tries to access it, PHP cannot find it and generates an "Undefined variable" warning.

To fix this error, you need to pass $a as an argument to the function assigned to $b or use the use keyword to import the $a variable into the function assigned to $b:

Option 1: Passing $a as an argument to $b

$a = function($v) {
    return $v;
};

$b = function($v, $a) {
    return $a($v);
};

echo $b('something', $a);

Option 2: Using use keyword to import $a into $b

$a = function($v) {
    return $v;
};

$b = function($v) use ($a) {
    return $a($v);
};

echo $b('something');
smolo
  • 737
  • 1
  • 15
  • 27