为了在PHP中快速编写好的toString()
方法,我正在寻找类似于java的ToStringBuilder
类。
更新:
我不是在询问如何使用或实施toString()
。我问的是像ToStringBuilder
这样强大的助手。 ToStringBuilder
节省了大量时间,因为它可以通过反射本身来计算出很多东西(例如集合,数组,嵌套类)。
答案 0 :(得分:3)
PHP实际上并不需要ToStringBuilder
;在几乎所有情况下,简单的print_r()
或var_dump()
都会执行转储任何变量(包括对象)以进行调试的工作。要获得更精确和可重现的表示,您可以使用var_export()
。例如:
class Test {
private $x = 'hello';
protected $y = 'world';
}
$t = new Test;
var_export($t);
var_dump($t);
print_r($t);
输出:
Test::__set_state(array(
'x' => 'hello',
'y' => 'world',
))
object(Test)#1 (2) {
["x":"Test":private]=>
string(5) "hello"
["y":protected]=>
string(5) "world"
}
Test Object
(
[x:Test:private] => hello
[y:protected] => world
)
var_export()
和print_r()
都使用第二个参数来返回字符串表示,而不是打印它们的输出。 var_dump()
没有此功能,因此您需要另一种方式:
ob_start();
var_dump($t);
$s = ob_get_clean();
echo "Object is $s\n";
另请参阅:print_r()
var_dump()
var_export()
旧答案
根据我对Java实现的理解,这是一个非常简约的PHP端口,我掀起了:
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);
}
}
这就是你在自己班级中使用它的方法:
class Person
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function __toString()
{
// use ToStringBuilder to form a respresentation
return ToStringBuilder::getInstance($this)
->append('name', $this->name)
->toString();
}
}
$person = new Person("John Doe");
echo $person;
// Person@00000000708ab57c0000000074a48d4e[name=John Doe]
序列化不是很精确,因为布尔值将用空字符串或1
表示。这可以改进:))
答案 1 :(得分:1)
这是一个快速实现,类似于您链接但略有不同的实现。输出非常类似var_export
(但不完全相同)并跨越多行:
<?php
class ToStringBuilder{
private $str;
public function __construct($my){
$this->str = get_class($my) . "(\n";
}
public static function create($my){
return new ToStringBuilder($my);
}
public function append($name, $var){
$this->str .= " " . $name . " => " . str_replace("\n", "\n ", var_export($var, true)) . ",\n";
return $this;
}
public function __toString(){
return $this->str . ")";
}
}
演示:http://codepad.org/9FJvpODp
要使用它,请参阅以下代码:
class Person{
private $name;
private $age;
private $hobbies;
public function __toString(){
return strval(ToStringBuilder::create($this)
->append("name", $this->name)
->append("age", $this->age)
->append("hobbies", $this->hobbies)
);
}
public function __construct($name, $age, $hobbies){
$this->name = $name;
$this->age = $age;
$this->hobbies = $hobbies;
}
}
echo new Person("hello", 18, array("swimming", "hiking"));