With so many parameter modes in PHP, I wanted to know exactly what ReflectionParameter
is going to return.
<?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";
}
Run the code here:
https://3v4l.org/pnXfM#v8.2.11
View the results here: