Home > php > StringBuilder class in PHP [PHP]

StringBuilder class in PHP [PHP]


In PHP you want to construct a long string from pieces.


Instead of string concatenation, it is better to collect the pieces in an array, then at the end put these pieces together in a string. For this we can use the following simple class that works similar to the Java StringBuilder class:

class StringBuilder 
    private $str = array();

    public function __construct() { }

    public function append($str) {
        $this->str[] = $str;
        return $this;
    public function toString() {
        return implode($this->str);


$sb = new StringBuilder();
print $sb->toString();


I found this nice solution in this thread. For append(), I proposed the method chaining possibility.

Categories: php Tags: , , ,
  1. Pavel
    April 19, 2013 at 21:57

    It’s not better. It’s ~10 times slower than ordinary concatenation. I’ve tested it. Test it if you don’t believe.

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 82 other followers

%d bloggers like this: