<?php
declare(strict_types=1);
function acceptBool(bool $x) {}
function acceptInt(int $x) {}
function acceptFloat(float $x) {}
function acceptString(string $x) {}
function acceptArray(array $x) {}
function acceptObject(object $x) {}
$functions = [
"bool" => "acceptBool",
"int" => "acceptInt",
"float" => "acceptFloat",
"string" => "acceptString",
"array" => "acceptArray",
"object" => "acceptObject",
];
$vars = [
"null" => null,
"bool" => true,
"int" => 1,
"float" => 3.14,
"numeric string" => "2.72",
"non-numeric string" => "elephphant",
"array" => [1, 2, 3],
"object" => new stdClass(),
];
foreach ($vars as $passedType => $var) {
foreach ($functions as $acceptedType => $function) {
if ($passedType === $acceptedType) {
continue;
}
echo str_pad($passedType, 18) . " -> " . str_pad($acceptedType, 10) . ": ";
try {
$function($var);
echo "success";
} catch(TypeError $e) {
echo "failure";
}
echo "\n";
}
}
preferences:
27.51 ms | 408 KiB | 6 Q