PHP 7 和严格 "resource" 类型
PHP 7 and strict "resource" types
PHP7 是否支持资源的严格类型化?如果是,怎么做?
例如:
declare (strict_types=1);
$ch = curl_init ();
test ($ch);
function test (resource $ch)
{
}
上面会报错:
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 ()
returns一个资源。
是否可以严格键入 test()
函数以支持 $ch variable
?
resource
不是 valid type,因此根据良好的旧 PHP/5 类型提示,它被假定为 class 名称。但是 curl_init()
不是 return 对象实例。
据我所知,无法指定资源。它可能不会那么有用,因为并非所有资源都是相同的:fopen()
生成的资源对 oci_parse()
.
没有用
如果要检查函数体中的资源,可以使用get_resource_type() (with is_resource()来防止出错),如:
is_resource($ch) && get_resource_type($ch) === 'curl'
从 PHP/8.0 开始,curl_init()
returns an object so you can now use CurlHandle
作为类型提示,
PHP 没有 type hint for resources 因为
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).
但是,您可以在 function/method 正文中使用 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)
)
);
}
}
然后您可以像这样在代码中使用它:
function test($ch)
{
assert_resource($ch);
// do something with resource
}
PHP7 是否支持资源的严格类型化?如果是,怎么做?
例如:
declare (strict_types=1);
$ch = curl_init ();
test ($ch);
function test (resource $ch)
{
}
上面会报错:
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 ()
returns一个资源。
是否可以严格键入 test()
函数以支持 $ch variable
?
resource
不是 valid type,因此根据良好的旧 PHP/5 类型提示,它被假定为 class 名称。但是 curl_init()
不是 return 对象实例。
据我所知,无法指定资源。它可能不会那么有用,因为并非所有资源都是相同的:fopen()
生成的资源对 oci_parse()
.
如果要检查函数体中的资源,可以使用get_resource_type() (with is_resource()来防止出错),如:
is_resource($ch) && get_resource_type($ch) === 'curl'
从 PHP/8.0 开始,curl_init()
returns an object so you can now use CurlHandle
作为类型提示,
PHP 没有 type hint for resources 因为
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).
但是,您可以在 function/method 正文中使用 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)
)
);
}
}
然后您可以像这样在代码中使用它:
function test($ch)
{
assert_resource($ch);
// do something with resource
}