July 28, 2010

Is there a way to override/rename/remap function in php?

Question by erotsppa

I know it’s possible in other language like C++ or Obj-c even (at runtime AND compile time) but is there a way to override/rename/remap function in php? So what I mean is, let’s say we want to replace the implementation of mysql_query. Is that possible?

SOME_REMAP_FUNCTION(mysql_query, new_mysql_query);

//and then you define your new function
function new_mysql_query(blah...) {
  //do something custom here
  //then call the original mysql_query
  mysql_query(blah...)
}

This way the rest of the code can transparently call the mysql_query function and not know that we inserted some custom code in the middle.

Answer by Cags

I believe if you make use of namespaces you can write a new function with the same name and ‘trick’ the system in that manner. Here’s a short blog I read about it on…

http://till.klampaeckel.de/blog/archives/105-Monkey-patching-in-PHP.html

Answer by Starx

If you have functions inside class. We can override it from other class inheriting it.

Example

class parent {
    function show() {
        echo "I am showing";
    }
}

class mychild extends parent {
    function show() {
        echo "I am child";
    }
}

$p = new parent;
$c = new mychild;

$p->show(); //call the show from parent
$c->show(); //call the show from mychild

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!