Damiano Barbati
Damiano Barbati

Reputation: 3496

PHP "this" context in anonymous function

I'm trying to call the "this" context within my anonymous function, called inside an object. I'm running PHP 5.5.9 and the php doc states that "$this can be used in anonymous functions." What's missing? Should I inject the context in some way binding the function to the object?

<?php

class Example
{
    public function __construct()
    {}

    public function test($func)
    {
        $func();
    }
}

$obj = new Example();

$obj->test(function(){
    print_r($this);
});

?>

Output:

PHP Notice:  Undefined variable: this on line 18

Upvotes: 0

Views: 2013

Answers (3)

ALXGTV
ALXGTV

Reputation: 362

Another solution would be to have $this as an argument of the function, and you just pass it via the call within your class $func($this).

<?php

class Example {
    …
    public function test($func)
    {
        $func($this);
    }
}

$obj = new Example();
$obj->test(function($this) {
    print_r($this);
});

?>

Upvotes: 0

arkascha
arkascha

Reputation: 42915

Well, you actually can use $this in an anonymous function. But you cannot use it outside of an object, that does not make sense. Note that you define that anonymous function outside your class definition. So what is $this mean to be in that case?

A simple solution would be to either define the function inside the class definition or to hand over the $this pointer to the function as an argument.

Upvotes: 2

Damiano Barbati
Damiano Barbati

Reputation: 3496

Solved with this... it definitely horrify me, any other solution (if exists) is well accepted.

<?php

class Example
{
    public function __construct()
    {}

    public function test($func)
    {
        $func = $func->bindTo($this, $this);
        $func();
    }
}

$obj = new Example();

$obj->test(function(){
    print_r($this);
});

?>

Upvotes: 1

Related Questions