不幸的是,你不能使用原始类型resource
作为类型提示。最新的类型提示系统更改为 PHP,标量类型提示 https://wiki.php.net/rfc/scalar_type_hints_v5,仅添加int
, float
, string
, and bool
.
您引用的错误之前曾出现过令人困惑,尤其是在标量类型提示的上下文中。让我为您模板化:
传递给 [Function] 的参数 [N] 必须是给定的 [Class]、[Type] 的实例
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 †
http://php.net/manual/en/reserved.other-reserved-words.php. 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
.
如果您想输入提示资源,我建议使用\SplFileObject
:
$handle = new \SplFileObject('myfile.csv', 'r');
function parseHandle(\SplFileObject $handle) { ... }
这不是世界上最好的事情,因为 \SplFileObject 有一些怪癖,但归根结底,如果您想在 PHP 中输入提示,您必须有一个数组、一个标量或一个类。