5

Is there a way how to execute closure in PHP5.3 within a context of an object?

class Test {
    public $name='John';

    function greet(){
        eval('echo "Hello, ".$this->name;');

        call_user_func(function(){
            echo "Goodbye, ".$this->name;
        });
    }
}
$c = new Test;
$c->greet();

The eval() would work fine, however call_user_func will have no access to $this. (Using $this when not in object context). I am passing "$this" as an argument to closure right now, but that's not exactly what I need.

1
  • Unfortunately call_user_func(array($this,function(){ .. })); wouldn't work, which would be ideal syntax for this. Commented Apr 5, 2011 at 9:26

4 Answers 4

6

Access to $this is not possible from lambda or closure as of PHP 5.3.6. You'd either have to assign $this to a temp var and use that with use (which means you will only have the public API available) or pass in/use the desired property. All shown elsewhere on this site, so I won't reiterate.

Access to $this is available in Trunk though for PHP.next: http://codepad.viper-7.com/PpBXa2

Sign up to request clarification or add additional context in comments.

2 Comments

How did you manage to answer questions so quickly btw? Is there a live question feed?
@roman I answered this one pretty late, didn't I? Don't know if there is a live feed. I just press F5 frequently :)
4

For an actual closure, this is about the only way to do it:

$obj = $this;
call_user_func(function () use ($obj) {
    echo "Goodbye, " . $obj->name;
});

It's probably more elegant to pass the object as parameter as suggested in the other answers (and probably as you're already doing).

1 Comment

Was about to suggest this. Usually you do $that = $this;. At least in JavaScript.
0

what about:

class Test {
    public $name='John';

    function greet(){
        eval('echo "Hello, ".$this->name;');

        call_user_func(function($obj){
            echo "Goodbye, ".$obj->name;
        }, $this);
    }
}
$c = new Test;
$c->greet();

1 Comment

That's what i'm using now, but it's not exactly setting the context.
0
call_user_func(function($name){
            echo "Goodbye, ".$name;
        }, $this->Name);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.