Is there a way of passing object context to an anonymous function without passing $this
as an argument?
class Foo {
function bar() {
$this->baz = 2;
# Fatal error: Using $this when not in object context
$echo_baz = function() { echo $this->baz; };
$echo_baz();
}
}
$f = new Foo();
$f->bar();
The syntax is simple: you can simply declare the anonymous function and make it execute by just calling it using the parenthesis at the end of the function. You can simply pass the parameters inside the immediate execution of the anonymous function as we have seen in the above example.
As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function. Example 3: In this example, we pass an anonymous function as a callback function to the setTimeout() method.
An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.
They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.
You can assign $this
to some variable and then use use
keyword to pass this variable to function, when defining function, though I'm not sure if it is easier to use. Anyway, here's an example:
class Foo {
function bar() {
$this->baz = 2;
$obj = $this;
$echo_baz = function() use($obj) { echo $obj->baz; };
$echo_baz();
}
}
$f = new Foo();
$f->bar();
It is worth noting that $obj
will be seen as standard object (rather than as $this
), so you won't be able to access private and protected members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With