note 101476 added to language.oop5.overloading

From: Date: Sun, 19 Dec 2010 11:12:34 +0000
Subject: note 101476 added to language.oop5.overloading
Groups: php.notes 
Request: Send a blank email to php-notes+get-175053@lists.php.net to get a copy of this message
Using anon functions, you can allow your class methods to be declared after your class is already set. Though you cannot use a class property as a function in any way (including for properties that are objects with their own __invoke() method) without triggering a fatal error, there is a workaround using an array property to store all these anon functions... <?php class Test { // generic class allowing dynamic addition of methods public $anon_list = array(); // list of all custom added methods function __call($fnc, $args) {return call_user_func_array($this->anon_list[$fnc], $args);} function __set($name, $val) {$this->anon_list[$name] = $val;} } // Example adding a new custom method $test = new Test; $test->do_something = function ($var1, $var2) {echo "custom called with $var1 and $var2\n";}; $test->do_something('asdf', 'test'); ?> Unfortunately, without access to $this within the anon functions, it's not really useful. You can "use ($test)" in your anon function, but that just makes it more complicated. ---- Server IP: 192.41.42.26 Probable Submitter: 66.90.145.185 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.overloading.php Edit -- https://master.php.net/note/edit/101476 Del: integrated -- https://master.php.net/note/delete/101476/integrated Del: useless -- https://master.php.net/note/delete/101476/useless Del: bad code -- https://master.php.net/note/delete/101476/bad+code Del: spam -- https://master.php.net/note/delete/101476/spam Del: non-english -- https://master.php.net/note/delete/101476/non-english Del: in docs -- https://master.php.net/note/delete/101476/in+docs Del: other reasons-- https://master.php.net/note/delete/101476 Reject -- https://master.php.net/note/reject/101476 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#175053) next »