Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call_user_func within class context (with $this defined)

Tags:

php

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.

like image 922
romaninsh Avatar asked Apr 05 '11 09:04

romaninsh


1 Answers

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

like image 71
Gordon Avatar answered Oct 16 '22 01:10

Gordon