小智 22
是的你可以.
下面是在php 5.4.x中运行时创建方法的方法.
匿名函数由从5.3.x开始的Closure类表示.从5.4.x开始,它添加了一个Closure :: bind静态方法,将匿名函数绑定到特定对象或类.
例:
class Foo {
private $methods = array();
public function addBar() {
$barFunc = function () {
var_dump($this->methods);
};
$this->methods['bar'] = \Closure::bind($barFunc, $this, get_class());
}
function __call($method, $args) {
if(is_callable($this->methods[$method]))
{
return call_user_func_array($this->methods[$method], $args);
}
}
}
$foo = new Foo;
$foo->addBar();
$foo->bar();
Run Code Online (Sandbox Code Playgroud)
有些玩弄整件事.似乎只有你可以做的事情ReflectionClass就是替换现有的方法.但即便如此也是间接的.
我实际上不知道任何基于类的语言,其中存在动态类(然后,我的知识非常有限).我已经看到它只在基于原型的语言(javascript,ruby,smalltalk)中完成.相反,在PHP 5.4中,您可以使用Closure并向现有对象添加新方法.
这是一个允许您对任何对象执行此类变换的类:
class Container
{
protected $target;
protected $className;
protected $methods = [];
public function __construct( $target )
{
$this->target = $target;
}
public function attach( $name, $method )
{
if ( !$this->className )
{
$this->className = get_class( $this->target );
}
$binded = Closure::bind( $method, $this->target, $this->className );
$this->methods[$name] = $binded;
}
public function __call( $name, $arguments )
{
if ( array_key_exists( $name, $this->methods ) )
{
return call_user_func_array( $this->methods[$name] , $arguments );
}
if ( method_exists( $this->target, $name ) )
{
return call_user_func_array(
array( $this->target, $name ),
$arguments
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它,您必须为构造函数提供现有对象.以下是一个小例子:
class Foo
{
private $bar = 'payload';
};
$foobar = new Foo;
// you initial object
$instance = new Container( $foobar );
$func = function ( $param )
{
return 'Get ' . $this->bar . ' and ' . $param;
};
$instance->attach('test', $func);
// setting up the whole thing
echo $instance->test('lorem ipsum');
// 'Get payload and lorem ipsum'
Run Code Online (Sandbox Code Playgroud)
不完全是你想要的,但AFAIK这是你可以得到的尽可能接近.
| 归档时间: |
|
| 查看次数: |
16958 次 |
| 最近记录: |