July 10, 2011

how to "inject" built-in php functions

Question by gadelat

How can i modify returning value of built-in php function without creating new function with another name and renaming all of used functions with previous name to new one?
e.g.

function time() {
    return time()-1000;
}

Of course this won’t pass, isn’t there something like “function time() extends time() {}” or similar?

Answer by Paul Dixon

With the APD PECL extension you can rename and override built-in functions.

//we want to call the original, so we rename it
rename_function('time', '_time()');

//now replace the built-in time with our override
override_function('time', '', 'return my_time();');

//and here's the override
function my_time($){
        return _time()-1000;  
}

APD is intended for debugging purposes, so this isn’t a technique you should really consider for production code.

Answer by Starx

Why would you want to override PHP’s function anyway? If some function does not do what you exactly want, then create your own function. If it overrides, use a different name or create a class and put the function inside it.

What you are trying to achieve is a wrong solution for a problem!!!

Some examples

Instead of function name time() you can make cTime()(custom Time)
Just like I create my own function for print_r() as printr() to print array in my way

or something like

class FUNCTIONS {
    public function time() {
        return time()-1000;
    }
}
//Now access using
FUNCTIONS::time();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!