doujiurong7210 2016-11-16 16:59
浏览 49
已采纳

将filehandle作为函数中的参数进行输入

I'm currently investigating some PHP-code and I'm trying to make it more up to date. I found a function, which retrieves a filehandle (via fopen).

The returntype is stream. I checked it with

$handle = fopen("myfile.csv", "r");
var_dump(get_resource_type($handle));

As mentioned, the type seems to be stream.

When I try to pass this object to a function, I can't force the type with stream.

public function parseHandle(stream $handle){}

ends up with this error-message:

Argument 1 passed to parseHandle must be an instance of stream, resource given.

When I try to change the signature to function parseHandle(resource $resource) it yields the following error:

Argument 1 passed to parseHandle must be an instance of resource, resource given

What is the correct datatype and how should I use it in the arguments?

I know I can use is_resource in the very first lines of my function to verify it, but I still wonder.

  • 写回答

1条回答 默认 最新

  • duanhuau567787 2016-11-16 17:29
    关注

    Unfortunately, you cannot use the primitive type resource as a type hint. The latest type hint system change to PHP, scalar type hints, only added int, float, string, and bool.

    The error you quote has come up before as confusing, especially in the context of the scalar type hints. Let me template it for you:

    Argument [N] passed to [Function] must be an instance of [Class], [Type] given

    The confusion arises because PHP allows classes to have the same name as documented primitives (bool, float, etc.) for all primitives before PHP 7, and for some in PHP 7 and later . So when you say stream $handle PHP is expecting $handle to be of class stream. Likewise resource $handle expects $handle to be of class resource.

    If you want to type hint resources, I suggest using an \SplFileObject:

    $handle = new \SplFileObject('myfile.csv', 'r');
    function parseHandle(\SplFileObject $handle) { ... }
    

    This is not the best thing in the world, as \SplFileObject has a few quirks, but at the end of the day, if you want to type hint it in PHP, you must either have an array, a scalar, or a class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题