I'm in the process of making an irc bot with PHP. While developing, I want to be able to dynamically load and unload classes/functions.
Mind you, the PHP is keep-alive.
ex:
Main File:
class stuff {
function stuff() { echo 'this'; }
function replaceFunction() {
remove(stuff);
add(stuff);
}
}
$stuff = new stuff();
I edit a function:
function stuff() { echo 'that'; }
So ideally, now that it's edited, all I have to do is trigger replaceFunction() to update the old function.
How can I make this actually work?
If the only thing you need is to have a class that has a function and you want to be able to exchange the functionality of that function by triggering the replaceFunction
, you can assign some closure to that class or similar:
class stuff {
private $callback;
public function __construct()
{
$this->callback = array($this, 'stuff');
}
public function __invoke()
{
call_user_func($this->callback);
}
private function stuff() { echo 'This'; }
function replace($function) {
$this->callback = $function;
}
}
$stuff = new stuff;
$stuff(); # original function
$stuff->replace(function() { echo 'That'; });
$stuff(); # replaced function
Or the short version:
$stuff = function() {echo 'This';};
$stuff(); # original function
$stuff = function() {echo 'That';};
$stuff(); # replaced function
The class has the benefit that you have more control about assigning and invoking the function.