4

为了toString()在 PHP 中快速编写好方法,我正在寻找类似ToStringBuilderjava 类的东西。

更新:我不是在问如何使用或实施toString(). 我在问一个像ToStringBuilderjava这样的强大助手。ToStringBuilder可以节省大量时间,因为它可以通过自己的反射找出很多东西(例如集合、数组、嵌套类)。

4

2 回答 2

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. 这可以改进:)

于 2012-12-11T08:09:48.517 回答
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"));
于 2012-12-11T08:36:18.890 回答