note 110845 added to closure.bind

From: Date: Fri, 14 Dec 2012 00:08:22 +0000
Subject: note 110845 added to closure.bind
Groups: php.notes 
Request: Send a blank email to php-notes+get-192523@lists.php.net to get a copy of this message
With this class and method, it's possible to do nice things, like add methods on the fly to an object. MetaTrait.php <?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(); ?> ---- Server IP: 69.147.83.199 Probable Submitter: 189.27.152.22 ---- Manual Page -- http://php.net/manual/en/closure.bind.php Edit -- https://master.php.net/note/edit/110845 Del: integrated -- https://master.php.net/note/delete/110845/integrated Del: useless -- https://master.php.net/note/delete/110845/useless Del: bad code -- https://master.php.net/note/delete/110845/bad+code Del: spam -- https://master.php.net/note/delete/110845/spam Del: non-english -- https://master.php.net/note/delete/110845/non-english Del: in docs -- https://master.php.net/note/delete/110845/in+docs Del: other reasons-- https://master.php.net/note/delete/110845 Reject -- https://master.php.net/note/reject/110845 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#192523) next »