PHP Variables in Anonymous Functions

PHP variables in anonymous functions

Yes, use a closure:

functionName($someArgument, function() use(&$variable) {
$variable = "something";
});

Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using &.

PHP: Is there a difference in passing a variable to anonymous function, and using closure function?

The closure function is useful when you don't have control over the arguments that are being passed. For instance, when you use array_map you can't add an additional parameter, it just receives the array elements. You can use the closure to access additional variables.

$string = "foo";
$array = ["abc", "def"];
$new_array = array_map(function($x) use ($string) {
return $string . $x;
}, $array);

Use variables inside an anonymous function, which is defined somewhere else

The point of the use keyword is to inherit/close over a particular environment state from the parent scope into the Closure when it's defined, e.g.

$foo = 1;

$fn = function() use ($foo) {
return $foo;
};

$foo = 2;

echo $fn(); // gives 1

If you want $foo to be closed over at a later point, either define the closure later or, if you want $foo to be always the current value (2), pass $foo as a regular parameter.

Accessing the variables from a PHP Anonymous Function

Not going to happen. You need to make the static function public. The anonymous function doesn't run inside the scope of MyClass, and therefore doesn't have access to private methods contained within it.

Access to out-of-scope variable within anonymous functions in Laravel (PHP)

This isn't a Laravel question, but a PHP one. Just add use ($variable) after the parameter list:

$posts = Post::whereHas('comments', function ($query) use ($id) {
$query->where('user_id', $id);
})->get();

Accessing outside variable using anonymous function as params

You have to use use as described in docs:

Closures may also inherit variables from the parent scope. Any such
variables must be declared in the function header. Inheriting
variables from the parent scope is not the same as using global
variables. Global variables exist in the global scope, which is the
same no matter what function is executing.

Code:

$result = '';
fetch("SELECT title FROM tbl", function($r) use (&$result) {
$result .= $r['title'];
});

But beware (taken from one of comments in previous link):

use() parameters are early binding - they use the variable's value at
the point where the lambda function is declared, rather than the point
where the lambda function is called (late binding).

Accessing outer variable in PHP 7 anonymous class

another solution could be

$outer = 'something';

$instance = new class($outer) {

private $outer;

public function __construct($outer) {
$this->outer = $outer
}

public function testing() {
var_dump($this->outer);
}
};


Related Topics



Leave a reply



Submit