PHP 7是否支持严格的资源类型?如果是这样,怎么样?
例如:
declare (strict_types=1);
$ch = curl_init ();
test ($ch);
function test (resource $ch)
{
}
Run Code Online (Sandbox Code Playgroud)
以上将给出错误:
致命错误:未捕获的TypeError:传递给test()的参数1必须是资源的实例,给定资源
var_dump on $ch显示它是资源(4,curl),手册说curl_init ()返回资源.
是否可以严格键入test()功能来支持$ch variable?
Gor*_*don 43
没有添加任何类型的资源提示,因为这会阻止资源从现有扩展的对象转移到某些已经完成的扩展(例如GMP).
但是,您可以is_resource()在函数/方法体内使用来验证传递的参数并根据需要进行处理.可重用的版本将是这样的断言:
function assert_resource($resource)
{
if (false === is_resource($resource)) {
throw new InvalidArgumentException(
sprintf(
'Argument must be a valid resource type. %s given.',
gettype($resource)
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在代码中使用它,如下所示:
function test($ch)
{
assert_resource($ch);
// do something with resource
}
Run Code Online (Sandbox Code Playgroud)