rockstardev
rockstardev

Reputation: 13527

Overriding var_dump globally?

I don't like the way var_dump prints out objects. I want to override it with this function:

function var_dump($object, $die = true) {
    print '<pre>';
    print_r($object);
    if ($die) die();
}

I know how to override it in my application, but is there a way to override it globally for all sites on a PHP config level?

Upvotes: 3

Views: 1835

Answers (2)

Alma Do
Alma Do

Reputation: 37365

You can not do that currently (via "good way") in PHP. And more - you shouldn't. var_dump() is doing right for what it's intended: plain output and nothing more. If you want to change that, then by definition you want some user-defined behavior. Therefore:

  • Create your own function. That is what you have now. User-defined functions are for user-defined behavior.

  • Or else, if you want to do it with var_dump() name by some reason, use namespace like:

      namespace Utils;
      function var_dump($var, $exit=true, $return=true)
      {
         $result = sprintf('<pre>%s</pre>', print_r($var, true));
         if($exit)
         {
            echo $result;
            exit;
         }
         if($return)
         {
            return $result;
         }
         echo $result;
      }
    

    so usage will look like:

      $obj = new StdClass();
      $str = \Utils\var_dump($obj, false);
      //do domething with $str
      echo $str; //or use second false
    
  • Worst case: runkit_function_redefine() Remember, this is evil. You should not do that because redefining goes against what is function and why it was defined. It is a global side-effect and you should avoid such behavior.

Upvotes: 5

m4t1t0
m4t1t0

Reputation: 5731

You can use the override_function: http://www.php.net/manual/en/function.override-function.php to replace the behavior of the var_dump function. If you want to include this piece of code in all of your sites, you can put this in your php.ini file:

php_value auto_prepend_file /path/to/file_where_you_override_function.php

Upvotes: 1

Related Questions