<?php
class Database {}
$fns = [
function ($str) {},
function ($str ="hello") {},
function (string $str) {},
function (string $str = null) {},
function (?string $str) {},
function (?Database $db) {},
function (Database $db = new Database()) {},
function (string|null $str) {},
function (string $str = "hello") {},
function (?string $str = "hello") {},
function (string|int $str) {},
function (string|null $str = null) {},
function (string|null $str = "hello") {},
];
echo "parameter\tallowsNull\tisOptional\tgetDefaultValue\tgetType\n";
foreach ($fns as $fn) {
$param = (new ReflectionFunction($fn))->getParameters()[0];
echo substr($param->__toString(), 26, -2)
. "\t" . json_encode($param->allowsNull())
. "\t" . json_encode($param->isOptional())
. "\t" . ($param->isDefaultValueAvailable() ? str_replace("\n", "", print_r($param->getDefaultValue(), true)) : "throws ReflectionException")
. "\t" . ($param->getType() ? get_class($param->getType()) : "null")
. "\n";
}
- Output for 8.2.10 - 8.2.11, 8.3.0
- parameter allowsNull isOptional getDefaultValue getType
$str true false throws ReflectionException null
$str = 'hello' true true hello null
string $str false false throws ReflectionException ReflectionNamedType
?string $str = NULL true true ReflectionNamedType
?string $str true false throws ReflectionException ReflectionNamedType
?Database $db true false throws ReflectionException ReflectionNamedType
Database $db = new \Database() false true Database Object() ReflectionNamedType
?string $str true false throws ReflectionException ReflectionNamedType
string $str = 'hello' false true hello ReflectionNamedType
?string $str = 'hello' true true hello ReflectionNamedType
string|int $str false false throws ReflectionException ReflectionUnionType
?string $str = NULL true true ReflectionNamedType
?string $str = 'hello' true true hello ReflectionNamedType
- Output for 8.0.11
- Fatal error: Constant expression contains invalid operations in /in/pnXfM on line 12
Process exited with code 255. - Output for 7.4.33
- Parse error: syntax error, unexpected '|', expecting variable (T_VARIABLE) in /in/pnXfM on line 13
Process exited with code 255. - Output for 5.6.40
- Parse error: syntax error, unexpected '?', expecting variable (T_VARIABLE) in /in/pnXfM on line 10
Process exited with code 255.
preferences:
173.73 ms | 1398 KiB | 13 Q