3v4l.org

run code in 300+ PHP versions simultaneously
<?php enum SpecialReturnValue { case NoReturn; case ReturnWithoutValue; case ReturnDollarThis; case ReturnVoid; case ReturnNever; } class ShouldTypeError { public $uniqueId; public function __construct($returnValue) { static $uniqueId = 0; $this->uniqueId = $uniqueId; $uniqueId++; if ($returnValue !== SpecialReturnValue::NoReturn) { if ($returnValue === SpecialReturnValue::ReturnWithoutValue) { return; } elseif ($returnValue === SpecialReturnValue::ReturnDollarThis) { return $this; } elseif ($returnValue === SpecialReturnValue::ReturnVoid) { return void; } elseif ($returnValue === SpecialReturnValue::ReturnNever) { return never; } return $returnValue; } } } const SOMECONST = 'Const hello'; enum SomeEnum { case Hearts; case Diamonds; case Clubs; case Spades; } function SomeFunction() { } $SomeFunctionClosure = function() { }; $SomeFunctionFirstClassCallable = SomeFunction(...); $someFunctionClosureFromCallabe = Closure::fromCallable('SomeFunction'); $arrowFunction = fn($a) => $a; $testcases = [ SpecialReturnValue::NoReturn, SpecialReturnValue::ReturnWithoutValue, SpecialReturnValue::ReturnDollarThis, new ShouldTypeError(SpecialReturnValue::NoReturn), SOMECONST, 'abc', 1, 1.23, null, true, false, ['a', 'b', 'c'], [6 => 'six', 7 => 'seven', 67 => 'six seven'], ['a' => 'a', 'b' => 'b', 'c' => 'c', 0 => 'Zero'], SpecialReturnValue::ReturnVoid, SpecialReturnValue::ReturnNever, SomeEnum::Spades, function() {}, $SomeFunctionClosure, $SomeFunctionFirstClassCallable, $someFunctionClosureFromCallabe, $arrowFunction, new DateTimeImmutable(), fopen('php://memory', 'w+'), ]; foreach($testcases as $testcase) { echo "--------------[ TESTCASE ]--------------\n"; var_dump($testcase); echo "\n"; try { $didReturn = new ShouldTypeError($testcase); if ($testcase === SpecialReturnValue::NoReturn) { echo "Success: without a return statement is always valid.\n"; } elseif ($testcase === SpecialReturnValue::ReturnWithoutValue) { echo "Success: a return statement without a value is always valid.\n"; } elseif ($testcase === SpecialReturnValue::ReturnDollarThis) { echo "Dubious: return \$this is dubious.\n"; echo "- it fullfills the return type, so it could be allowed.\n"; echo "- but returning anything from a constructor is nonsense, because it is discarded by \"new\".\n"; echo " As shown by the fourth testcase new SomeTypeError(SpecialReturnValue::NoReturn).\n"; } else { echo "Error: why is it not a return TypeError?\n"; } if ($didReturn instanceof ShouldTypeError) { echo "Created uniqueId ".$didReturn->uniqueId."\n"; } else { echo "Failed to new a ShouldTypeError.\n"; } } catch (Throwable $ex) { echo "Success: throwable: ".$ex->getMessage()."\n"; } }

preferences:
27.5 ms | 405 KiB | 5 Q