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).
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.
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 &
.
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);
}
};
Call an anonymous function with a local variable as parameter
The definition of the anonymous function includes the declaration of an argument named n
, which hides the n
variable from the outer scope. The function declaration is creating a new local variable that is nil unless an argument is actually passed into the function, but the timer function that calls your anonymous function isn't expecting to pass anything in, so the function-local n
stays nil.
You can fix it by simply removing the argument declaration from the anonymous function, but keep the usage of n
within the function. Then it will capture the n
variable from the outer scope, which has the value returned from hs.notify(...)
.
function main()
local n = hs.notify(...)
print(n) -- `hs.notify: Title (0x7fbd2b5318f8)`
hs.timer.doAfter(1, function() -- <== no argument
print(n) -- nil
n:withdraw() -- error: attempt to index a nil value (local 'n')
end)
end
lambda function accessing outside variable
You can "capture" the i
when creating the lambda
lambda x, i=i: x%i==0
This will set the i
in the lambda's context equal to whatever i
was when it was created. you could also say lambda x, n=i: x%n==0
if you wanted. It's not exactly capture, but it gets you what you need.
It's an issue of lookup that's analogous to the following with defined functions:
i = "original"
def print_i1():
print(i) # prints "changed" when called below
def print_i2(s=i): # default set at function creation, not call
print(s) # prints "original" when called below
i = "changed"
print_i1()
print_i2()
How can I pass arguments to anonymous functions in JavaScript?
Your specific case can simply be corrected to be working:
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function() { alert(myMessage); };
</script>
This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.
For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there
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();
Why it's not possible to access variables from parent/outer scope in anonymous functions on PHP?
You can capture the variable you need with use.
$world = 'world';
$func = function() use ($world) {
echo 'hello ' . $world;
};
$func();
// hello world
Related Topics
PHP Threading Call to a PHP Function Asynchronously
Get Everything Between ≪Tag≫ and ≪/Tag≫ With PHP
How to Insert HTML to PHP Domnode
How to Avoid Echoing Character 65279 in PHP
"Unknown Modifier 'G' In..." When Using Preg_Match in PHP
Difference Between JavaScript and PHP
Does Sleep Time Count For Execution Time Limit
How to Remove All Specific Characters At the End of a String in PHP
Unformat Money When Parsing in PHP
Reading and Writing Configuration Files
Implementing Condition in Xpath
Including a Remote File in PHP
Remove the Last Character from a String
Accurate Way to Measure Execution Times of PHP Scripts
: Operator (The 'Elvis Operator') in PHP
MySQL Datetime Fields and Daylight Savings Time - How to Reference the "Extra" Hour