title: PHP - Increment a variable in a function return
body: <p>Here are 2 versions of a very simple class. </p>
  
  <p>Only the <code>getCounterIncrement()</code> function is different in the 2 versions.</p>
  
  <h3>Version 1</h3>
  
  <pre><code>class Counter {
  
    protected $counter;
  
    public function __construct() {
  
      $this-&gt;counter = 0;
    }
  
    public function getCounterIncrement() {
  
      return $this-&gt;counter++;
    }
  }
  
  $counter = new Counter;
  print $counter-&gt;getCounterIncrement(); // outputs 0
  print $counter-&gt;getCounterIncrement(); // outputs 1
  </code></pre>
  
  <h3>Version 2</h3>
  
  <pre><code>class Counter {
  
    protected $counter;
  
    public function __construct() {
  
      $this-&gt;counter = 0;
    }
  
    public function getCounterIncrement() {
  
      $this-&gt;counter++;
      return $this-&gt;counter;
    }
  }
  
  $counter = new Counter;
  print $counter-&gt;getCounterIncrement(); // outputs 1
  print $counter-&gt;getCounterIncrement(); // outputs 2
  </code></pre>
  
  <h3>Questions</h3>
  
  <ul>
  <li>Why is the output different in the 2 versions?</li>
  <li>Is one of the 2 versions better than the other in terms of coding standards?</li>
  <li>Would there be a nicer / better way to code that?</li>
  </ul>