call_user_func within class context (with $this defined)

前端 未结 4 376
野趣味
野趣味 2020-12-21 01:09

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(\'         


        
相关标签:
4条回答
  • 2020-12-21 01:21
    call_user_func(function($name){
                echo "Goodbye, ".$name;
            }, $this->Name);
    
    0 讨论(0)
  • 2020-12-21 01:23

    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

    0 讨论(0)
  • 2020-12-21 01:24

    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();
    
    0 讨论(0)
  • 2020-12-21 01:31

    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).

    0 讨论(0)
提交回复
热议问题