StringBuilder for PHP

Solution 1:

Note:

This answer is from 2010, there might be stringbuilders that can improve the performance by now (judging from the comments below). I have not worked with php for a long time so my knowledge is not up to date. This answer might be out dated.

The following question might provide interesting information as well, all tough their conclusion seem to be the same.

php String Concatenation, Performance


Why do you want to use a StringBuilder? Strings in php are mutable. Therefore performance is not an issue.

Just build string like this

$string = "start";
$string .= "appended string";
$string .= "appended string";
etc.

Solution 2:

You can use sprintf which is only a basic version but requires no extra libraries, examples Follow

$String = "Firstname %s, lastname %s, Age %d";
echo sprintf($String,"Robert","Pitt",22);

And also handles type casting and position replacements:

$format = "The %2$s contains %1$d monkeys. That's a nice %2$s full of %1$d monkeys.";
sprintf($format, $num, $location);

All though i do like the look of jacob's answer :)

taker a look at the great functionality of t his function and its sister function here: http://php.net/manual/en/function.sprintf.php

Solution 3:

There are some implementations out there, however I don't see why you would need a StringBuilder in PHP,at least not for performance reasons. Plain string concatenation in PHP is faster than sprintf or the impelementation Jacob suggested.

Solution 4:

You don't need StringBuilder or StringBuffer in PHP , PHP is super handy I offer you , using from hereDoc and NowDoc if you you wish to keep PyString :

$YourString = "start";
$YourString .= <<<'EOD'

appended string
Example of string
spanning multiple lines
using nowdoc syntax.

EOD;

$YourString .= <<<buffer

appended string
Example of string
spanning multiple lines
using heredoc syntax.

appended string

appended string

buffer;

Solution 5:

Answer of @Amir, gave me inspiration to the fact that in PHP if you want 'named parameters' or 'positional' parameters, you don't need sprintf, but HERE_DOC/NOW_DOC works perfect. You can even use this inside of a class for properties and call getters.

class MyClass{

     private $property;

     private $stock; // some other object with getter 'getSomeProperty()'

     function __toString(){

         $localvar = 'Localvar';
         $localvar2 = 'Localvar2';
         return <<<HERE_DOC
           {{ 
              fqsn: {$this->stock->getSomeProperty()},
              property: {$this->property},
              localvar: {$localvar},
              localvar2: $localvar2
           }}
HERE_DOC;
      } // end __toString()
 } // end MyClass