I wanted to reuse a class of mine, which generated a <ul> with links, only this time I wanted to alter the link text using a custom function (closure) in the constructor.

<?= $this->generateUl($existing_arg1, $existing_arg2, function($args){ //do stuff } ); ?>

Inside the class constructor, I set the following:

public function __construct($existing_arg1, $existing_arg2, Callable $closure = null)
{
    $this->closure = $closure;
}

And here’s the wee catch: You can’t call it like a normal method, $this->closure($args); You need to assign it to a standard variable for whatever reason.

    /** 
     *  @param ESOS_Entity_Org $org
     *  @return string
     */
    private Function generateLinkText(ESOS_Entity_Organisation $org)
    {
        if(!$this->closure)
        {
            // This is my default functionality
            return $org->getName();
        }
        // There are two ways of doing this next bit:
        // $this->closure($args); won't work but $closure($args) will!
        // $closure = $this->closure; 
        // return $closure($org);

                // Here's the better way:
                return call_user_func($this->closure,$org);
    }

Doing this has made me realise just how awesome Callables can be, you could inject in all manner of functionality into a class! Play around with it!

Advertisements