PHP在运行时创建类方法 [英] php create class method at runtime
问题描述
我想知道是否有一种方法可以在运行时使用php将新方法附加到类上. 我的意思是,不是在实例级别上,而是直接在类上,以便所有新创建的实例都具有此新方法. 这样的事情可以通过反思来完成吗?
I am wondering if there is a way to attach a new method to a class at runtime, in php. I mean, not on an instance level but directly to the class, so that all newly created instances, have this new method. Can such a thing be done with reflection?
谢谢
推荐答案
是的,可以.
下面是在php 5.4.x中的运行时中创建方法的方法.
Below is the way to create method in runtime in php 5.4.x.
匿名函数由从5.3.x开始的Closure类表示.从5.4.x开始,它添加了 Closure :: bind 静态方法来将匿名函数绑定到特定的对象或类.
The anonymous function is represented by Closure class started from 5.3.x. From 5.4.x, it add a Closure::bind static method to bind the anonymous function to a particular object or class.
示例:
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();
这篇关于PHP在运行时创建类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!