<?php
set_error_handler('handleTypehint');
function a(int $b){};
a(5); // works
a(true); // error
a('bla'); // error
a([]); // error
// handleTypeHintIsBelow v
function handleTypehint($errorLevel, $errorMessage)
{
static $map =
[
'int' => 'integer',
'bool' => 'boolean',
'str' => 'string'
];
// handle only recoverable errors
if ($errorLevel !== E_RECOVERABLE_ERROR)
return false;
// Check this is the right error message we are trying to handle
if(preg_match('/^Argument (\d)+ passed to (?:(\w+)::)?(\w+)\(\) must be an instance of (\w+), (\w+) given/', $errorMessage, $match))
{
$expectedType = $match[4];
$givenType = $match[5];
if($expectedType === $givenType || $map[$expectedType] === $givenType)
return true;
}
return false;
}
1