erotsppa
erotsppa

Reputation: 15021

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

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.

Upvotes: 2

Views: 2718

Answers (7)

RobertPitt
RobertPitt

Reputation: 57268

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

Upvotes: 0

Starx
Starx

Reputation: 78981

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

Upvotes: 0

Powerlord
Powerlord

Reputation: 88796

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.

Upvotes: 0

symcbean
symcbean

Reputation: 48357

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.

Upvotes: 2

Peter O&#39;Callaghan
Peter O&#39;Callaghan

Reputation: 6186

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

Upvotes: 2

n00dle
n00dle

Reputation: 6043

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.

Upvotes: 0

Mchl
Mchl

Reputation: 62377

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.

Upvotes: 0

Related Questions