Home > php > StringBuilder class in PHP [PHP]

StringBuilder class in PHP [PHP]

Problem

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

Solution

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

Usage:

$sb = new StringBuilder();
$sb->append("one")->append("two");
print $sb->toString();

Credits

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

About these ads
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

Follow

Get every new post delivered to your Inbox.

Join 72 other followers

%d bloggers like this: