class Foo {
public $var;
}
$foo = new Foo();
$foo->bar = function() { echo "Hello World\n"; };
$foo->bar->__invoke();
Not pretty but that's how I've always done it. class Foo {
public $var;
}
$foo = new Foo();
$foo->bar = function() { echo "Hello World\n"; };
$foo->bar->__invoke();
Not pretty but that's how I've always done it.Example:
$c = new stdClass;
$c->test = function() { return 'hello world'; };
echo ($c->test)(); $response = (new Response())->handle ();
So it's not completely alien in PHP.I don't know how these patterns develop - it's very common in JS, but somewhat rare in PHP. Maybe it has to do with the average level of the programmer in each? Or jQuery's noConflict() helped it along with everybody starting with (function($) {})(jQuery), thus integrating IIFE into their active repertoire.
I don't remember (and haven't found in quickly searching) PSR saying anything about that, but that could explain a difference in usage, too.
Anonymous functions and classes are being used more and more, but PHP isn't fundamentally event-driven like JS so there's less need to hand them out like candy and nest them several levels deep. Most of the closures I do use on a daily basis are callback functions to things like array_filter() and preg_replace_callback(), not event handlers like every jQuery code ever written.
<?php trait MetaTrait {
private $methods = array();
public function addMethod($methodName, $methodCallable)
{
if (!is_callable($methodCallable)) {
throw new InvalidArgumentException('Second param must be callable');
}
$this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
}
public function __call($methodName, array $args)
{
if (isset($this->methods[$methodName])) {
return call_user_func_array($this->methods[$methodName], $args);
}
throw RunTimeException('There is no method with the given name to call');
}
}
?>test.php <?php require 'MetaTrait.php';
class HackThursday { use MetaTrait;
private $dayOfWeek = 'Thursday';
}$test = new HackThursday(); $test->addMethod('when', function () { return $this->dayOfWeek; });
echo $test->when();