php is resource,PHP is_resource 用法 手册 | 示例代码

Note that is_resource() is unreliable. It considers closed resources as false:

$a=fopen(,'r');var_dump(is_resource($a));var_dump(is_scalar($a));//bool(true)

//bool(false)fclose($a);var_dump(is_resource($a));var_dump(is_scalar($a));//bool(false)

//bool(false)?>

That's the reason why some other people here have been confused and devised some complex (bad) "solutions" to detect resources...

There's a much better solution... In fact, I just showed it above, but here it is again with a more complete example:

$a =fopen(,'r');var_dump(is_resource($a));var_dump(is_scalar($a));var_dump(is_object($a));var_dump(is_array($a));var_dump(is_null($a));//bool(true)

//bool(false)

//bool(false)

//bool(false)

//bool(false)

?>

So how do you check if something is a resource?

Like this!

$a =fopen(,'r');$isResource=is_resource($a) ($a!==null&& !is_scalar($a) && !is_array($a) && !is_object($a));var_dump($isResource);//bool(true)

fclose($a);

var_dump(is_resource($a));//bool(false)

$isResource=is_resource($a) ($a!==null&& !is_scalar($a) && !is_array($a) && !is_object($a));var_dump($isResource);//bool(true)

?>

How it works:

- An active resource is a resource, so check that first for efficiency.

- Then branch to check what the variable is NOT:

- A resource is never NULL. (We do that check via `!== null` for efficiency).

- A resource is never Scalar (int, float, string, bool).

- A resource is never an array.

- A resource is never an object.

- Only one variable type remains if all of the above checks succeeded: IF it's NOT any of the above, then it's a closed resource!

Just surfed by and saw the bad and hacky methods other people had left, and wanted to help out with this proper technique. Good luck, everyone!

PS: The core problem is that is_resource() does a "loose" check for "living resource". I wish that it had a $strict parameter for "any resource" instead of these user-workarounds being necessary.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值