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