Created
May 17, 2014 04:02
-
-
Save memememomo/b0072bb8eabb720d6a7b to your computer and use it in GitHub Desktop.
PHPで動的にメソッドを追加する方法 ref: http://qiita.com/uchiko/items/1c97a1ae0cd98b1b229d
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Object | |
{ | |
static private $_methods = array(); | |
static public function addMethod($name, Closure $cb) | |
{ | |
self::$_methods[$name] = $cb; | |
} | |
public function __call($name, array $args) | |
{ | |
$func = self::$_methods[$name]; | |
return call_user_func_array($func->bindTo($this, get_class($this)), $args); | |
} | |
public function add($a, $b) | |
{ | |
return $a + $b; | |
} | |
} | |
foreach (array(10,100,1000) as $base) { | |
Object::addMethod('add'.$base, function($number) use ($base) { | |
return $this->add($number, $base); | |
}); | |
} | |
$object = new Object(); | |
echo $object->add10(1)."\n"; | |
echo $object->add100(1)."\n"; | |
echo $object->add1000(1)."\n"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Object | |
{ | |
static private $_methods = array(); | |
static public function addMethod($name, Closure $cb) | |
{ | |
self::$_methods[$name] = $cb; | |
} | |
public function __call($name, array $args) | |
{ | |
array_unshift($args, $this); | |
return call_user_func_array(self::$_methods[$name], $args); | |
} | |
public function add($a, $b) | |
{ | |
return $a + $b; | |
} | |
} | |
foreach (array(10,100,1000) as $base) { | |
Object::addMethod('add'.$base, function($self, $number) use ($base) { | |
return $self->add($number, $base); | |
}); | |
} | |
$object = new Object(); | |
echo $object->add10(1)."\n"; | |
echo $object->add100(1)."\n"; | |
echo $object->add1000(1)."\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment