Advertisement
Guest User

Untitled

a guest
May 31st, 2011
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.45 KB | None | 0 0
  1. <?php
  2.  
  3. // Vgl. http://de.wikipedia.org/wiki/Delegat_%28.NET%29#Beispiel_in_Visual_C.23
  4.  
  5. namespace X
  6. {
  7.     use Closure;
  8.  
  9.     abstract class Delegate
  10.     {
  11.         protected $closure;
  12.  
  13.         public function __construct(Closure $closure)
  14.         {
  15.             $this->closure = $closure;
  16.         }
  17.  
  18.         public function __invoke()
  19.         {
  20.             return call_user_func_array($this->closure, func_get_args());
  21.         }
  22.     }
  23. }
  24.  
  25. namespace Wikipedia\DelegateSample
  26. {
  27.     use X\Delegate;
  28.  
  29.     class MyStringDelegate extends Delegate {}
  30.  
  31.     class MainClass
  32.     {
  33.         public static function main()
  34.         {
  35.             $mc = new MainClass();
  36.  
  37.             $delegateUpper = new MyStringDelegate(function ($s) use ($mc) {
  38.                 return $mc->upperFunction($s); });
  39.  
  40.             $delegateLower = new MyStringDelegate(function ($s) use ($mc) {
  41.                 return $mc->lowerFunction($s); });
  42.  
  43.             self::doSomething($delegateUpper, 'Hello World');
  44.  
  45.             self::doSomething($delegateLower, 'Hello World');
  46.         }
  47.  
  48.         public static function doSomething(MyStringDelegate $delegate, $input)
  49.         {
  50.             echo $delegate($input), "\n";
  51.         }
  52.  
  53.         public function upperFunction($s)
  54.         {
  55.             return mb_strtoupper($s);
  56.         }
  57.  
  58.         public function lowerFunction($s)
  59.         {
  60.             return mb_strtolower($s);
  61.         }
  62.     }
  63.  
  64.     MainClass::main();
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement