我定义了一个这样的函数:
private function mediaExist(string $entry) { ...
Run Code Online (Sandbox Code Playgroud)
我收到这种类型的错误:
... must be an instance of string, string given, called in ...
Run Code Online (Sandbox Code Playgroud)
有什么帮助吗?
PHP 类型提示仅适用于类或数组:
function foo(array $bar, stdClass $object)
{//fine
}
Run Code Online (Sandbox Code Playgroud)
但是您不能对基元/标量或资源类型进行类型提示:
function bar(int $num, string $str)
{}
Run Code Online (Sandbox Code Playgroud)
这将调用自动加载器,它会尝试查找int和string类的类定义,而这显然不存在。
这背后的理由非常简单。PHP 是一种松散类型语言,数字字符串可以通过类型转换转换为 int 或 float:
$foo = '123';
$bar = $foo*2;//foo's value is used as an int -> 123*2
Run Code Online (Sandbox Code Playgroud)
引入类型提示是为了提高语言的面向对象能力:类/接口应该能够通过使用(除其他外)类型提示来强制执行契约。
如果要确保给定值是字符串,可以使用强制转换或类型检查函数:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
就资源而言(例如文件处理程序),修复起来也很容易:
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)
);
);
}
}
Run Code Online (Sandbox Code Playgroud)
最后,开发大型 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 = '')
{
}
Run Code Online (Sandbox Code Playgroud)