3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Entity { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; return $this; } } class DB { public function findByName($name) { if ($name === 'belette') { return new Entity($name); } return false; } } class Test { private $db; public function __construct(DB $db) { $this->db = $db; } public function getEntity($name) { $entity = $this->db->findByName($name); $new = false; if (false === $entity) { $entity = new Entity(); $entity->setName($name); $this->db->insert($entity); $new = true; } return new class($entity, $new) { private $new; public $entity; public function __construct(Entity $entity, $new) { $this->entity = $entity; $this->new = $new; } public function isNew() { return $this->new; } }; } } $db = new DB(); $test = new Test($db); $result = $test->getEntity('blaireau'); if ($result->isNew()) { echo "L'entité 'blaireau' n'existait pas en base\n"; } var_dump($result->entity->getName());
Output for 7.1.0 - 7.1.20, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Entity::__construct(), 0 passed in /in/WqggW on line 44 and exactly 1 expected in /in/WqggW:5 Stack trace: #0 /in/WqggW(44): Entity->__construct() #1 /in/WqggW(70): Test->getEntity('blaireau') #2 {main} thrown in /in/WqggW on line 5
Process exited with code 255.
Output for 7.0.0 - 7.0.20
Warning: Missing argument 1 for Entity::__construct(), called in /in/WqggW on line 44 and defined in /in/WqggW on line 5 Notice: Undefined variable: name in /in/WqggW on line 7 Fatal error: Uncaught Error: Call to undefined method DB::insert() in /in/WqggW:46 Stack trace: #0 /in/WqggW(70): Test->getEntity('blaireau') #1 {main} thrown in /in/WqggW on line 46
Process exited with code 255.
Output for 5.5.24 - 5.5.35, 5.6.8 - 5.6.28
Parse error: syntax error, unexpected 'class' (T_CLASS) in /in/WqggW on line 50
Process exited with code 255.

preferences:
164.45 ms | 402 KiB | 183 Q