PHP 类型提示仅适用于类或数组:
function foo(array $bar, stdClass $object)
{//fine
}
但您不能键入提示原语/标量或资源类型:
function bar(int $num, string $str)
{}
这将调用自动加载器,它会尝试查找 int 和 string 类的类定义,这些类显然不存在。
这背后的理由很简单。 PHP 是一种松散类型的语言,数字字符串可以通过 type-juggling 转换为 int 或 float:
$foo = '123';
$bar = $foo*2;//foo's value is used as an int -> 123*2
引入类型提示是为了提高语言的 OO 功能:类/接口应该能够通过使用(除其他外)类型提示来强制执行合同。
如果要确保给定值是字符串,可以使用强制转换或类型检查函数:
function foo($string)
{
$sureString = (string) $string;//cast to string
if ($sureString != $string)
{//loose comparison, if they are not equal, the argument could not be converted to a string reliable
throw new InvalidArgumentException(__FUNCTION__.' expects a string argument, '.get_type($string).' given');
}
}
就资源而言(例如文件处理程序),修复起来同样容易:
function foobar(/* resource hint is not allowed */ $resource)
{
if (!is_resource($resource))
{
throw new InvalidArgumentException(
sprintf(
'%s expects a resource, %s given',
__FUNCTION__,
get_type($resource)
);
);
}
}
最后,在开发大型 PHP 项目时,最好的办法是使用 doc-blocks 和一个不错的 IDE。当您调用函数/方法时,IDE 将使用文档块告诉您预期的类型。确保满足这些标准是程序员的工作:
/**
* Some documentation: what this function does, and how the arguments
* are being used
* @param array $data
* @param string $key
* @param string $errorMsg = ''
* @return mixed
* @throws InvalidArgumentException
**/
function doStuff(array $data, $key, $errorMsg = '')
{
}