PHP does not need ToStringBuilder ; In almost all cases, a simple print_r() or var_dump() will perform the task of resetting any variable (including objects) for debugging purposes. To get a more accurate and reproducible representation, you can use var_export() . For instance:
class Test { private $x = 'hello'; protected $y = 'world'; } $t = new Test; var_export($t); var_dump($t); print_r($t);
Output:
Test::__set_state(array( 'x' => 'hello', 'y' => 'world', )) object(Test)
Both var_export() and print_r() take a second parameter to return a string representation instead of printing their output. var_dump() does not have this function, so you need another way:
ob_start(); var_dump($t); $s = ob_get_clean(); echo "Object is $s\n";
See also: print_r() var_dump() var_export()
Old answer
From my understanding of the Java implementation, this is a very minimalistic port for PHP, which I whipped:
class ToStringBuilder { private $o; // the object to build a string for private $h; // a hash of parameters public function __construct($obj) { $this->o = $obj; $this->h = array(); } public function append($key, $value) { $this->h[] = "$key=$value"; // you could also use this for a full representation of the PHP type // "$key=" . var_export($value, true) return $this; // make it chainable } // final serialization public function toString() { return get_class($this->o) . '@' . spl_object_hash($this->o) . '[' . join(',', $this->h) . ']'; } // help method to avoid a separate $x = new ToStringBuilder() statement public function getInstance($obj) { return new self($obj); } }
Here's how you could use it in your class:
class Person { private $name; public function __construct($name) { $this->name = $name; } public function __toString() {
Serialization is not very accurate, because Booleans will be represented either by an empty string, or simply 1 . It can be improved :)