Advertisement
NilsCorver

PHP Dynamic Static Methods

Nov 9th, 2011
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.11 KB | None | 0 0
  1. <?php
  2.  
  3. class Dynamic {
  4.     const RE_MethodName = '@[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*@';
  5.    
  6.     static protected $container = array();
  7.    
  8.     static public function attach ($name, $method) {
  9.         if(!is_string($name))
  10.             throw new \InvalidArgumentException('$name should be a string.');
  11.         if(!preg_match(self::RE_MethodName, $name))
  12.             throw new \InvalidArgumentException('$name is not a valid method name');
  13.         if(!is_callable($method))
  14.             throw new \InvalidArgumentException('$method should be callable.');
  15.        
  16.         self::$container[$name] = $method;
  17.     }
  18.    
  19.     static public function __callStatic ($name, $arguments) {
  20.         return isset(self::$container[$name])
  21.             ? call_user_func_array(self::$container[$name], $arguments)
  22.             : null;
  23.     }
  24.    
  25.     protected function __construct () {}
  26. }
  27.  
  28. Dynamic::attach('urlsafe', function ($value) {
  29.     $value = strtolower($value);
  30.     $value = preg_replace('@[^a-z0-9_#%:]+@', '-', $value);
  31.     return trim($value, '-');
  32. });
  33.  
  34. echo Dynamic::urlsafe('My precious URL + something else.');
  35. echo Dynamic::does_not_exist('The ABC.');
  36.  
  37. // urlsafe        : my-precious-url-something-else
  38. // does_not_exist :
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement