Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Created October 11, 2023 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/082458088988e32256a827f9b7491e17 to your computer and use it in GitHub Desktop.
Save mindplay-dk/082458088988e32256a827f9b7491e17 to your computer and use it in GitHub Desktop.
PHP ReflectionParameter overview

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:

https://docs.google.com/spreadsheets/d/e/2PACX-1vR5js_sH3J2kC4xKkoPtsbH2R2ucFAZPI119k350iopKvDQXZcZ0CVQKwGqo9fOYgdVP0S-hj7T8yYq/pubhtml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment