Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass object context to an anonymous function?

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();
like image 242
Tim Avatar asked Jun 13 '11 12:06

Tim


People also ask

Can you pass parameters to anonymous function JavaScript?

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.

Can anonymous function be passed as a parameter?

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.

Can you assign anonymous function to a variable?

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.

Can you assign an anonymous function to a variable and pass it as an argument to another function in JavaScript?

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.


1 Answers

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.

like image 175
binaryLV Avatar answered Jan 01 '23 19:01

binaryLV