Page 1 of 1

Override PHP builtin functions

Posted: Mon Aug 28, 2006 3:38 pm
by sparkle
How do i override the print_r() function?
I don't want to create another function, i just want to change print_r's content to echo a '<pre>' in front of it's output.

Thanx.

Posted: Mon Aug 28, 2006 3:58 pm
by Oren
Can't you just print a <pre> tag before calling print_r(), and one </pre> after?

Posted: Mon Aug 28, 2006 4:03 pm
by Luke
Ummm can't you just do this:

Code: Select all

function my_print_r($var){
    echo "<pre>";
    print_r($var);
    echo "</pre>";
}

Posted: Mon Aug 28, 2006 4:23 pm
by feyd
Several of the available debuggers and a couple of php extensions can rename functions (including PHP's built-in ones.) Although I would just use the type of function Ninja posted. It's less hassle and is far more portable.

Posted: Mon Aug 28, 2006 5:08 pm
by pickle
I've actually written a custom function to do just this, plus a little more:

Code: Select all

function dumpArray($p_array)
{
  $backtrace = debug_backtrace();
  $file = $backtrace[0]['file'];
  $line = $backtrace[0]['line'];
 
  echo '<pre>';
  echo "File: $file<br />";
  echo "Line: $line<br />";
  print_r($p_array);
  echo '</pre>';
}
This function outputs what file & line the function was called from - useful if you've got multiple calls in a file & you've forgotten where you put them.

If you don't want to have to worry about including a long absolute or tricky relative filename in each file you want to use this, you have two options (that I know of):
  1. You can put this function in a file then put that file in your include path. phpinfo() should tell you where that is. What this'll do is allow you to just call include('customfunctions.php') from anywhere, and PHP will find the file you want.
  2. You can put this function in a file and then make that file automatically included at the head of every PHP document. Perhaps a little overkill, but if this is just a private server, it shouldn't be too bad. You can set the file to automatically include in php.ini.

Posted: Mon Aug 28, 2006 7:37 pm
by RobertGonzalez
That is a kickin' function pickle. I think I'll be absconding with that shortly.

Posted: Tue Aug 29, 2006 5:03 am
by sparkle
thanks for the answers. I was just wondering if PHP is capable of doing those things, as i think any desktop language(at least C and Delphi) can.

I really wanted to override print_r in a framework, because everyone knows that function, so if i create another one, there's one extra function to learn.
Anyways, a real kicker there pickle ;) It's really nice and simple. Thanx.

Posted: Tue Aug 29, 2006 9:58 am
by pickle
Everah wrote:That is a kickin' function pickle. I think I'll be absconding with that shortly.
Feel free. The licensing is extremely affordable at only $15 per home computer, or $250 per computer for the enterprise edition ;)