3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Model { protected $comments; public function __construct() { $this->comments = new class { public function count() { $responses = [ 1, 2, 3, "Error: could not connect to database", 5 ]; $rand = rand(0, 4); if (is_string($responses[$rand])) { throw new Exception($responses[$rand]); } return $responses[$rand]; } }; } } class Post extends Model { public function commentCount() { static $cache; return $cache?: $cache = $this->comments->count(); } } class Logger { public static function log(string $log): void { echo $log; } } class CommentCount { private $count; public function __construct(int $count) { $this->count = $count; } public function getCount(): int { return $this->count; } } class Post extends Model { public function commentCount(): CommentCount { try { return new CommentCount($this->comments->count()); } catch (Exception $e) { Logger::log($e->getMessage()); return new CommentCount(0); } } } $post = new Post(); $commentCount = $post->commentCount(); var_dump($commentCount->getCount()); var_dump($commentCount->getCount()); var_dump($commentCount->getCount()); var_dump($commentCount->getCount()); var_dump($commentCount->getCount());
Output for 7.4.0 - 7.4.5
Fatal error: Cannot declare class Post, because the name is already in use in /in/odnch on line 65
Process exited with code 255.
Output for 7.2.0 - 7.2.29, 7.3.0 - 7.3.17
Fatal error: Cannot declare class Post, because the name is already in use in /in/odnch on line 77
Process exited with code 255.

preferences:
78.97 ms | 402 KiB | 59 Q