- array_map: documentation ( source)
- debug_backtrace: documentation ( source)
<?php
function strict()
{
$backtrace = debug_backtrace(0, 2);
if (false === $backtrace || count($backtrace) !== 2) {
throw new \RuntimeException('strict() must be called from within a function');
}
$expectedTypes = func_get_args();
$receivedTypes = array_map('gettype', $backtrace[1]['args']);
if (count($expectedTypes) !== count($receivedTypes)) {
throw new \InvalidArgumentException('Got ' . count($receivedTypes) . ' arguments, expected ' . count($expectedTypes));
}
for ($i = 0; $i < count($expectedTypes); $i++) {
if ($expectedTypes[$i] !== $receivedTypes[$i]) {
throw new \InvalidArgumentException('Expected argument ' . ($i + 1) . ' to be of type ' . $expectedTypes[$i] . ', received ' . $receivedTypes[$i]);
}
}
}
function myargs($a, $b)
{
strict('string', 'integer');
echo 'Hello'.PHP_EOL;
}
myargs('hello', 4);
myargs(4, 'oof');