3v4l.org

run code in 300+ PHP versions simultaneously
<?php /* readonly */ class ImmutableCounter { public function __construct(private readonly int $count) {} public function add1(): self { return new self($this->count + 1); } public function value(): int { return $this->count; } } // assuming the proposed RFC is in place, this is now possible: class MutableCounter extends ImmutableCounter { public function __construct(private int $count) {} public function add1(): self { return new self(++$this->count); } public function value(): int { return $this->count; } } $counter1 = new ImmutableCounter(0); $counter2 = $counter1->add1(); $counter3 = $counter2->add1(); var_dump([$counter1->value(), $counter2->value(), $counter3->value()]); $mutableCounter1 = new MutableCounter(0); $mutableCounter2 = $mutableCounter1->add1(); $mutableCounter3 = $mutableCounter2->add1(); var_dump([$mutableCounter1->value(), $mutableCounter2->value(), $mutableCounter3->value()]);
Output for 8.1.0 - 8.1.12
array(3) { [0]=> int(0) [1]=> int(1) [2]=> int(2) } array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(2) }
Output for 8.0.1 - 8.0.25
Parse error: syntax error, unexpected identifier "int", expecting variable in /in/IDhRY on line 4
Process exited with code 255.
Output for 7.4.0 - 7.4.33
Parse error: syntax error, unexpected 'private' (T_PRIVATE), expecting variable (T_VARIABLE) in /in/IDhRY on line 4
Process exited with code 255.

preferences:
207.67 ms | 1395 KiB | 76 Q