3

This is for fun only, don't scream please.

I would like to rewrite the content of a class's methods at runtime (I mean, without modifying the file, only replacing/editing the code in memory), is that possible?

Using reflection, or anything else?

Don't close this question please, I'm looking for another answer than runkit.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
  • 8
    Ahhhhhhhhhhhhhhhhhhhhhhhhhh!!!!!!!!!!!!!!!! – k to the z Apr 11 '11 at 20:58
  • I think one possible (but wrong way) to go about this would be to call a `file_get_contents` on the file, make the changes needed, then calling an `eval`. The downside is that you'll have to essentially create a loader because it would be a massive pain (or infinite loop if not careful) to have a file load itself. – Mr. Llama Apr 11 '11 at 21:00
  • possible duplicate of [PHP runtime class modification](http://stackoverflow.com/questions/1593497/php-runtime-class-modification) – netcoder Apr 11 '11 at 21:05
  • 1
    I don't think it should be closed because the only solution proposed in the old duplicate was "runkit", and runkit is very very old... I'm looking for ideas ! – Matthieu Napoli Apr 11 '11 at 21:09
  • If you don't want to use runkit, the the only other option is [classkit](http://www.php.net/manual/en/function.classkit-method-redefine.php). Likewise old and am not sure if it works on current PHP setups. – mario Apr 11 '11 at 21:20
  • @Matthieu, runkit/classkit (should) still work, and is the only effective way to get this done if the class has already been loaded. – Charles Apr 11 '11 at 21:20
  • @Charles "the class has already been loaded" : Well it doesn't have to. What about reading the PHP file in memory (php://memory), modifying it in memory, and then include "php://memory" ? – Matthieu Napoli Apr 11 '11 at 21:24
  • @Matthieu, it happens that [`php://memory` is a filehandle](http://php.net/manual/en/wrappers.php.php#example-284), so you wouldn't be able to hand it to `include`. You'd may as well use `eval` here to get the same effect. (Okay, you could use [`data:`](http://www.php.net/manual/en/wrappers.data.php) here, but that's restricted when `allow_url_include` is disabled, which it'd better be.) – Charles Apr 11 '11 at 21:27

1 Answers1

0

Why not simply create a new class that inherits from the one you want to modify and overwrite it's methods?

<?php
class MySimpleXML extends SimpleXMLElement {
    public function themethodiwanttooverwrite() {
        //...
    }
}
?>

As long as the method isn't marked as final...

Carlos Precioso
  • 2,731
  • 3
  • 21
  • 24