|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2008-08-26 20:08 UTC] colder@php.net
[2008-08-26 20:17 UTC] david at grudl dot com
[2008-08-26 22:14 UTC] colder@php.net
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Dec 03 23:00:01 2025 UTC |
Description: ------------ It should be useful to encapsulate PHP pseudotype callback using new magic method __invoke(). But this type of "callable" objects are not distinguishable by any interface or class name (compare it with ArrayAccess or Countable interfaces). // this is simple callback encapsulation class Callback { private $callback; public function __construct($callback) { $this->callback = $callback; } public function __invoke() { $args = func_get_args(); return call_user_func_array($this->callback, $args); } } // a Callback object: $callback = new Callback(array('MyClass', 'anyMethod')); // a Closure object: $closure = function() { ... }; The problem: there is nothing common between Callback and Closure object, what can be used (for example) as type hinting. First solution using interface: interface Callable { function __invoke() } class Callback implements Callable { ... } function event(Callable $obj) { $obj($sender, $param); } event($callback); event($closure); // do not work The class Closure is not Callable implementor thus it do not work. Problematic is __invoke method's parameters too. The other way: class Callback extends Closure { ... } // do not work function event(Closure $obj) { $obj($sender, $param); } event($callback); event($closure); This is not possible, because Closure is final. Solution is make Closure non-final. The third way - create static factory to encapsulate PHP callback as Closure: function event(Closure $obj) { $obj($sender, $param); } $callback = Closure::factory(array('MyClass', 'anyMethod')); event($callback); event($closure); Maybe the most easy way.