note 96579 added to functions.anonymous

From: Date: Fri, 05 Mar 2010 22:42:57 +0000
Subject: note 96579 added to functions.anonymous
Groups: php.notes 
Request: Send a blank email to php-notes+get-166719@lists.php.net to get a copy of this message
Anonymous functions are great for events! <?php class Event { public static $events = array(); public static function bind($event, $callback, $obj = null) { if (!self::$events[$event]) { self::$events[$event] = array(); } self::$events[$event][] = ($obj === null) ? $callback : array($obj, $callback); } public static function run($event) { if (!self::$events[$event]) return; foreach (self::$events[$event] as $callback) { if (call_user_func($callback) === false) break; } } } function hello() { echo "Hello from function hello()\n"; } class Foo { function hello() { echo "Hello from foo->hello()\n"; } } class Bar { function hello() { echo "Hello from Bar::hello()\n"; } } $foo = new Foo(); // bind a global function to the 'test' event Event::bind("test", "hello"); // bind an anonymous function Event::bind("test", function() { echo "Hello from anonymous function\n"; }); // bind an class function on an instance Event::bind("test", "hello", $foo); // bind a static class function Event::bind("test", "Bar::hello"); Event::run("test"); /* Output Hello from function hello() Hello from anonymous function Hello from foo->hello() Hello from Bar::hello() */ ?> ---- Server IP: 69.147.83.197 Probable Submitter: 99.61.33.46 ---- Manual Page -- http://www.php.net/manual/en/functions.anonymous.php Edit -- https://master.php.net/note/edit/96579 Del: integrated -- https://master.php.net/note/delete/96579/integrated Del: useless -- https://master.php.net/note/delete/96579/useless Del: bad code -- https://master.php.net/note/delete/96579/bad+code Del: spam -- https://master.php.net/note/delete/96579/spam Del: non-english -- https://master.php.net/note/delete/96579/non-english Del: in docs -- https://master.php.net/note/delete/96579/in+docs Del: other reasons-- https://master.php.net/note/delete/96579 Reject -- https://master.php.net/note/reject/96579 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#166719) next »