1

Is it possible to add an anonymous function to an object, and call it within the object. See below for example code. Calling closure assigned to object property directly and Anonymous function for a method of an object describe calling it directly, not within the object. Thank you

class myClass
{
    public function go()
    {
        $this->scope;
    }
}

$myObj=new myClass();
$myObj->scope=function()
{
    echo('Print This!');
};
$myObj->go();
Community
  • 1
  • 1
user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

2

$this->scope needs to called/executed within myClass:go. For example: -

<?php
class Example {
    protected
        $callback;

    public function setCallback($callback) {
        $this->callback = $callback;
    }

    public function invoke() {
        call_user_func($this->callback);
    }
}

$example = new Example;

$example->setCallback(function(){
    echo 'Hello World';
});

$example->invoke();
/*
    Hello World
*/

Anthony.

Anthony Sterling
  • 2,451
  • 16
  • 10