modify a method/function at runtime

2019-04-23 09:27发布

I've been looking at the php reflection methods, what i want to do is inject some code after the method is opened and before any return value, for example i want to change:

function foo($bar)
{
    $foo = $bar ;
    return $foo ;
}

And inject some code into it like:

function foo($bar)
{
    //some code here
    $foo = $bar ;
    //some code here
    return $foo ;
}

possible?

7条回答
看我几分像从前
2楼-- · 2019-04-23 09:55

This isn't possible, at least not in the way you are after. As the comment suggested, reflection is for getting information about classes/functions, not modifying them.

There is a PHP extension called Runkit which I believe provides this type of functionality - http://www.php.net/manual/en/book.runkit.php, however this isn't going to be installed by default on the vast majority of hosts out there.

There may be a different way of doing this though. Perhaps if you could give some more info on what you're trying to do, and why you can't modify the function in question, we might be able to provide some pointers. E.g. is the function you want to modify a core PHP function, or code in a third party library which you don't want to edit?

查看更多
登录 后发表回答