user1032531
user1032531

Reputation: 26301

Adding a PHP anonymous function to an object

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();

Upvotes: 1

Views: 397

Answers (1)

Anthony Sterling
Anthony Sterling

Reputation: 2441

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

Upvotes: 2

Related Questions