PHP 7和严格的“资源"类型 [英] PHP 7 and strict "resource" types
问题描述
PHP 7是否支持严格输入资源?如果可以,怎么办?
Does PHP 7 support strict typing for resources? If so, how?
例如:
declare (strict_types=1);
$ch = curl_init ();
test ($ch);
function test (resource $ch)
{
}
上面将给出错误:
致命错误:未捕获的TypeError:传递给test()的参数1必须是资源的实例,资源已给定
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of resource, resource given
$ch
上的var_dump显示它为 resource(4,curl),并且手册中说curl_init ()
返回资源.
A var_dump on $ch
reveals it to be resource(4, curl), and the manual says curl_init ()
returns a resource.
是否完全可以严格键入test()
函数以支持$ch variable
?
Is it at all possible to strictly type the test()
function to support the $ch variable
?
推荐答案
PHP没有资源的类型提示因为
PHP does not have a type hint for resources because
不添加资源的类型提示,因为这将阻止从资源移动到现有扩展的对象,某些扩展已经完成了这些操作(例如GMP).
No type hint for resources is added, as this would prevent moving from resources to objects for existing extensions, which some have already done (e.g. GMP).
但是,您可以在函数/方法主体中使用 is_resource()
来验证传递的参数并根据需要进行处理.可重用的版本将是这样的断言:
However, you can use is_resource()
within the function/method body to verify the passed argument and handle it as needed. A reusable version would be an assertion like this:
function assert_resource($resource)
{
if (false === is_resource($resource)) {
throw new InvalidArgumentException(
sprintf(
'Argument must be a valid resource type. %s given.',
gettype($resource)
)
);
}
}
然后您可以在代码中像这样使用
which you could then use within your code like that:
function test($ch)
{
assert_resource($ch);
// do something with resource
}
这篇关于PHP 7和严格的“资源"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!