title: PHP Method Chaining and Strings
body: <p>This is an interesting quirk I found while method chaining and I'm having difficulty bypassing it. I'm sure there's a solution or another way. It's tough to explain but I'll do my best.</p>
  
  <p>Example:</p>
  
  <p>You have three functions which are part of a class, as well as 2 protected properties as follows.</p>
  
  <pre><code>class Chain {
  
    protected $_str  = '';
    protected $_part = 0;
  
    public function __toString() {
      return implode(' ', $this-&gt;_str);
    }
  
    public function AAA () {
      $this-&gt;_str[$this-&gt;_part] = 'AAA';
      $this-&gt;_part++;
      return $this;
    }
  
    public function BBB () {
      $this-&gt;_str[$this-&gt;_part] = 'BBB';
      $this-&gt;_part++;
      return $this;
    }
  
    public function wrap ($str) {
      $part = $this-&gt;_part - 1;
      $this-&gt;_str[$part] = "({$str})";
      return $this;
    }
  
  }
  </code></pre>
  
  <p>Now when chaining these methods and specifically using the wrap method, the strings from previous chains are unintentionally appended. Example:</p>
  
  <pre><code>$chain = new Chain();
  $chain-&gt;AAA()-&gt;BBB()-&gt;wrap($chain-&gt;AAA());
  echo $chain;
  </code></pre>
  
  <p>What you would expect the string to look like is <code>AAA BBB (AAA)</code>.</p>
  
  <p>However, what actually returns is <code>AAA BBB (AAA BBB AAA)</code>.</p>
  
  <p>Why is it that <code>wrap()</code> takes all the previous methods called within the chain instead of only the method that's actually wrapped by it? What is the best way around this assuming there is one?</p>