3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php // note that copy() is a proper alternative to __clone() interface Any { function getHash(); function equals($other); } class Mutable implements Any { protected $baz; function __construct(string $baz){ $this->setBaz($baz); } function setBaz(string $baz){ $this->baz = $baz; } function getBaz(){ return $this->baz; } function getHash(){ return Immutable::CLASS . "|" . spl_object_hash($this); } function equals($other){ return $this->getHash() === $other->getHash(); } function copy(){ return new static($this->baz); } } class Immutable implements Any { protected $baz; function __construct(string $baz){ $this->baz = $baz; } function getHash(){ return Mutable::CLASS . "|" . $this->baz; } function equals($other){ return $this->getHash() === $other->getHash(); } function copy(){ return $this; } } var_dump((new Immutable("baz"))->equals(new Immutable("baz"))); // true var_dump((new Immutable("bar"))->equals(new Immutable("bar"))); // true var_dump((new Mutable("baz"))->equals(new Mutable("baz"))); // false var_dump((new Mutable("bar"))->equals(new Mutable("bar"))); // false
based on 2Redc
Output for 7.0.0 - 7.2.0
bool(true) bool(true) bool(false) bool(false)
Output for 5.5.24 - 5.6.28
Catchable fatal error: Argument 1 passed to Immutable::__construct() must be an instance of string, string given, called in /in/ha14g on line 61 and defined in /in/ha14g on line 44
Process exited with code 255.
Output for 5.4.2 - 5.4.45
Parse error: syntax error, unexpected 'CLASS' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /in/ha14g on line 28
Process exited with code 255.
Output for 5.3.17 - 5.3.29
Parse error: syntax error, unexpected T_CLASS, expecting T_STRING or T_VARIABLE or '$' in /in/ha14g on line 28
Process exited with code 255.