xmwwgq
Last Updated: February 25, 2016
·
692
· ravinsharma7

Anonymous functions as methods in classes

Today I was reading the book DSL in Action, from mannings. Then somewhere along the way, I wondered if I could use anonymous function as methods in a class.

POC attempt:

class ClassFoo{
    $foo_anonymous = function(){
        echo 'Obama';
    }
}

Tried to run the script, result was not pleasing for me:

Parse error: syntax error, unexpected '$foo_anonymous' (T_VARIABLE), expecting function (T_FUNCTION) in ...

Sad, and disappointed. I wanted to find a workaround, a solution.

  • First I thought of using __call(), then I imaged what kind of nightmare it can be... So I threw that first idea out of the window.

  • Second attempt, I tried to understand what was wrong. From the error message, PHP parser was too stupid to understand, I want an anonymous function in a class. So I attempt to write a stupid function wrapper to handle PHP's stupidity.

class ClassFoo{
    public function __construct(){
        $this->stupid_wrapper();
    }
    public function stupid_wrapper(){
        $this->foo = function(){ 
            echo "Dropbox";
        };
        $this->foo2 = function(){
            echo "Condoleezza Rice";
        };
    }
}

Script ran, now I need to access the method.

// First attempt to access method
$classfoo = new ClassFoo;
$classfoo->foo();
// $classfoo->foo; //nothing, also doesnt call the anonymous method
Fatal error: Call to undefined method ClassFoo::foo()

PHP does not see my method. No choice but need to be a bit verbose to access the anonymous method.

$classfoo = new ClassFoo;
$foo = $classfoo->foo;
$foo2 = $classfoo->foo2;
$foo();
$foo2();

Works, result:
DropboxCondoleezza Rice

Conclusion:

  1. Anonymous method can be used in PHP classes, but you need a thin wrapper around it. Because there is a limitation of PHP anonymous function syntax in the context of a PHP class.

Discussions:

  1. I'm not sure in what context anonymous methods can be useful. If you have an idea, please enlighten me.

  2. Closures are object in PHP. Maybe there is some kind of performance impact using it like this in PHP. I do not know yet.

  3. The Object is very decomposable in this setting, You can overload and override methods very easily.

  4. You might lose the ability to use mutator keywords like private, protected for your methods. This depends whether you declare your variables beforehand.

  5. Anything else you know, enlighten me.

If you find this a good read, give me thumbs up.
Thanx.