Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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();
share|improve this question
Not sure if it is but you need to define your property first – php_nub_qq Jun 5 at 13:40
@php_nub_qq. No effect when defining the property first. – user1032531 Jun 5 at 13:42

1 Answer

up vote 1 down vote accepted

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

share|improve this answer
Thanks Anthony, Seems call_user_func() is what I needed. – user1032531 Jun 5 at 13:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.