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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置