public
Created

PHP __toString() method for debugging

  • Download Gist
README.md
Markdown

Use

In object: $this->__toString(); OR echo $this;

In object, var_dump: $this->__toString('var_dump');

Print out a different object: $class->__toString('print_r', $object);

__toString().php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
<?php
 
class Foo {
 
/**
* Prints out the contents of the object when used as a string
*
* @return string
*/
function __toString()
{
$args = func_get_args();
$method = ( ! empty($args)) ? $args[0] : "print_r";
$output = '<pre>';
if($method == "var_dump")
{
ob_start();
var_dump($this);
$output .= ob_get_contents();
ob_end_clean();
}
else if($method == "var_export")
{
ob_start();
var_export($this);
$output .= ob_get_contents();
ob_end_clean();
}
else
{
$output .= print_r($this, TRUE);
}
return $output . '</pre>';
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.