2012-12-11 30 views
4

爲了在PHP中快速編寫好的toString()方法我正在尋找類似於java的ToStringBuilder類。有沒有ToStringBuilder for php?

更新: 我不是在問如何使用或實施toString()。我在問關於java的ToStringBuilder這樣一個強大的幫手。 ToStringBuilder是一個很大的時間保護程序,因爲它可以通過自己反射(例如集合,數組,嵌套類)來計算出很多事情。

+1

是的你可以。這就是所謂的'類型鑄造'你可以谷歌爲此或檢查[這裏](http://stackoverflow.com/questions/11857052/php-typecasting)總之你可以做'echo(string)$ int;' –

回答

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; 
// [email protected][name=John Doe] 

序列化是不是非常精確,因爲布爾值要麼爲空字符串或只是1表示。這可以改善:)

+0

你也可以談談魔術常數__CLASS__我想? – artragis

+0

@artragis是的,我完全錯過了關於'ToStringBuilder'的一點,所以我重寫了整個答案。 –

+0

非常感謝您的答覆!如果你正在尋找類似'ReflectionToStringBuilder'的東西,''print_r()','var_dump()'和'var_export()'是完美的。如果你想限制數據量,上面提到的'ToStringBuilder'實現是一個神的起點。 – BetaRide

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