PHP:如何重命名方法? [英] PHP: How is it possible to rename methods?
问题描述
是否可以在运行时重命名 PHP 5.2 中的类方法?是否可以使用反射来做到这一点?
Is it possible to rename a class method in PHP 5.2 during run time? Is it possible to do that using Reflection?
给定:
class Test
{
public function myMethod()
{
echo 'in my method';
}
}
我希望能够将 myMethod()
重命名为 oldMethod()
以便稍后我这样做:
I want to be able to rename myMethod()
to oldMethod()
so that later I do this:
$test = new Test();
$test->oldMethod(); // in my method
$test->myMethod(); // run time error: method does not exist
推荐答案
来自下面问题的评论:
因为我想在类上安装调用事件处理程序,而类不知道它,所以我知道用户在实际调用该方法之前正在从类中调用该方法.
because I would like to install call event handlers on classes, without the classes knowing about it, so I would know that the user is calling a method from a class before that method is actually called.
解决方案:使用装饰器.
Solution: use a Decorator.
class EventDecorator
{
protected $_instance;
public function __construct($instance)
{
$this->_instance = $instance;
}
public function __get($prop)
{
printf('Getting %s in %s', $prop, get_class($this->_instance));
return $this->_instance->$prop;
}
public function __set($prop, $val)
{
printf('Setting %s with %s in %s',
$prop, $val, get_class($this->_instance));
return $this->_instance->$prop = $val;
}
public function __call($method, $args)
{
printf('Calling %s with %s in %s',
$method, var_export($args, TRUE), get_class($this->_instance));
return call_user_func_array(array($this->_instance, $method), $args);
}
}
然后你可以将任何类包装到其中:
Then you can wrap any class into it:
class Foo
{
public $prop;
public function doSomething() {}
}
$foo = new EventDecorator(new Foo);
$foo->prop = 'bar'; // Setting prop with bar in Foo
$foo->prop; // Getting prop in Foo
$foo->doSomething('something');
// Calling doSomething with array (0 => 'something',) in Foo
这可以充实以提供前后挂钩.您还可以让装饰器使用 主题/观察者模式,并向注册到装饰器.上述方法比使用 runkit 的monkeypatching 随机方法更易于维护和理解.
This can be fleshed out to provide pre and post hooks. You could also make the Decorator use the Subject/Observer Pattern and fire events to whatever other object registered to the decorator. The above approach is more maintainable and understandable than monkeypatching random methods with runkit.
附加说明:
- 您可能对 Symfonys EventDispatcher 组件感兴趣.
- 如果您追求面向方面的编程,请阅读 http://sebastian-bergmann.de/archives/573-Current-State-of-AOP-for-PHP.html - 它是从 2006 年开始的,但此后该领域没有太大变化.
- 如果您追求横向重用,您会喜欢 PHP 的 Trait 功能在接下来的几个版本之一.
- You might be interested in the Symfonys EventDispatcher component.
- If you are after Aspect Oriented programming, read http://sebastian-bergmann.de/archives/573-Current-State-of-AOP-for-PHP.html - it's from 2006 but there is not much changed in that field since then.
- If you are after horizontal reuse, you will like PHP's Trait functionality that is supposed to be in one of the next few versions.
这篇关于PHP:如何重命名方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!