tags:

views:

58

answers:

6

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.

A: 

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.

Mchl
It's the PECL RunKit extension that allows this
Mark Baker
A: 

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.

ianhales
A: 

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

Cags
+1  A: 

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.

symcbean
A: 

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.

R. Bemrose
A: 

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
Starx