Skip to content

Instantly share code, notes, and snippets.

@timw4mail
Created January 12, 2012 19:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timw4mail/1602576 to your computer and use it in GitHub Desktop.
Save timw4mail/1602576 to your computer and use it in GitHub Desktop.
PHP __toString() method for debugging

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);

<?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>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment