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



Question:

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.


Solution:1

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


Solution:2

As ianhales says you can do this using the APD extension or alternatively with the runkit Both extensions have lots of other useful in them but both can break your system in strange and exotic ways if you apply them in internet facing webservers.

A better solution is to re-write the code when you deploy it (this can be done automatically e.g. using sed) maybe making use of auto_prepend.

C.


Solution:3

Not in PHP as downloaded from php.net. There's an extension that allows this though.

And if these are mysql functions you're after, better look into extending mysqli class.


Solution:4

http://php.net/manual/en/function.override-function.php This might be of some use. The top comment sounds exactly like the example you posted. It does use a PECL extension though.


Solution:5

A better idea would be to use an abstraction layer from the start, such as PDO. PDO ships with PHP 5.1 and newer, and is available as a PECL extension for PHP 5.0.x.


Solution:6

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  


Solution:7

Why dont you just wrap your functions within a namespace?

namespace MySQL  {      function connect()      {           //Blah      }  }  

and then use like so:

<?php    mysql_connect(); //Native Version  MySQL\connect(); //Your Version  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »