3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * Try it out */ $user = (new Api)->user(1); echo "Got user ".$user->id; function phpdoc_params(ReflectionMethod $method) : array { // Retrieve the full PhpDoc comment block $doc = $method->getDocComment(); // Trim each line from space and star chars $lines = array_map(function($line){ return trim($line, " *"); }, explode("\n", $doc)); // Retain lines that start with an @ $lines = array_filter($lines, function($line){ return strpos($line, "@") === 0; }); $args = []; // Push each value in the corresponding @param array foreach($lines as $line){ list($param, $value) = explode(' ', $line, 2); $args[$param][] = $value; } return $args; } class Api { /** * @param int $id * @return User * @throws ReflectionException * @endpoint users */ public function user(int $id) : User { return $this->request($this->endpoint(__METHOD__), $id); } /** * @param string $method * @return string * @throws ReflectionException */ protected function endpoint(string $method) : string { $reflection = new \ReflectionMethod($method); $params = phpdoc_params($reflection); return $params['@endpoint'][0] ?? null; } /** * @param string $endpoint * @param $param * @return User */ protected function request(string $endpoint, $param) { switch($endpoint){ case 'users': return new User($param); default: throw new InvalidArgumentException("Invalid endpoint"); } } } /** * Class User */ class User { public $id; public function __construct($id) { $this->id = $id; } }
Output for 8.4.1 - 8.4.2
Deprecated: Calling ReflectionMethod::__construct() with 1 argument is deprecated, use ReflectionMethod::createFromMethodName() instead in /in/UuIop on line 53 Got user 1
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.27, 8.3.0 - 8.3.15
Got user 1

preferences:
121.03 ms | 412 KiB | 6 Q