Is it possible to rename a class method in PHP 5.2 during run time? Is it possible to do that using Reflection?
Given:
class Test
{
public function myMethod()
{
echo 'in my method';
}
}
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
Using Runkits runkit_method_rename you can do this.
For all of you who are asking why you would need this, I have an idea that is very similar. My idea is to attempt to rename an entire PHP Class on the fly. It would be used, in my case, for an IRC Chat bot that I would have load and instantiate plugins on the fly, so that I would no need to reboot the bot and uptime would be very long. This would include renaming of pre-loaded classes of the same name as the class I would be attempting to load, so that there would be no conflict and it would run properly.
For example:
I have
$bot
running on irc.example.comI have the plugin test.php installed and working, now when this is loaded into memory I can alter the file test.php without any change to
$bot
So I update test.php
Now I want to cause it to load into
$bot
, but$bot
already has a test load in it, and it would conflict if I attempted to include test.php againso instead, we run a rename function to rename class test to class test[sha1 of a counter]
and then we include 'test.php'
and there we have it, an updated test plugin installed and loaded into memory on
$bot
with no reboot.This is all theory, but it's something to think about before instantly flaming someone for their ideas with the "Why would you even need this" attitude.
I mean, let's be honest here. What are the odds that you're a super genius who knows everything there is to know about programming and would know what everyone would or wouldn't need?
From comment below question:
Solution: use a Decorator.
Then you can wrap any class into it:
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.
Additional notes: