Advertisement
Omnikron13

Draft 'Add Method' PHP Trait

Sep 8th, 2014
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.06 KB | None | 0 0
  1. <?php
  2.  
  3. trait TEnhance {
  4.     //Array to hold new method Closures
  5.     protected static $added_methods = [];
  6.  
  7.     //Adds a new method to the class
  8.     public static function add_method($name, $closure) {
  9.         static::$added_methods[get_called_class()][$name] = $closure;
  10.     }
  11.  
  12.     //Looks through the inheritance hierachy for an added method with
  13.     //the given name, returning the Closure if found, throwing if not
  14.     protected static function find_method($name) {
  15.         $class = get_called_class();
  16.         if(
  17.             array_key_exists($class, static::$added_methods) &&
  18.             array_key_exists($name, static::$added_methods[$class])
  19.         ) return static::$added_methods[$class][$name];
  20.         $parent = get_parent_class($class);
  21.         if(!$parent) throw new Exception('No such method =(');
  22.         return $parent::find_method($name);
  23.     }
  24.  
  25.     //
  26.     public function __call($name, $args) {
  27.         return call_user_func_array(
  28.             static::find_method($name)->bindTo($this, $this),
  29.             $args
  30.         );
  31.     }
  32. }
  33.  
  34. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement