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();
2
  • Not sure if it is but you need to define your property first Commented Jun 5, 2013 at 13:40
  • @php_nub_qq. No effect when defining the property first. Commented Jun 5, 2013 at 13:42

1 Answer 1

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.

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

1 Comment

Thanks Anthony, Seems call_user_func() is what I needed.

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.