Variable handling 函数
在线手册:中文 英文
PHP手册

is_resource

(PHP 4, PHP 5)

is_resource 检测变量是否为资源类型

描述

bool is_resource ( mixed $var )

如果给出的参数 varresource 类型,is_resource() 返回 TRUE,否则返回 FALSE

查看 resource 类型文档获取更多的信息。


Variable handling 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 检测变量是否为资源类型

用户评论:

btleffler [AT] gmail [DOT] com (12-May-2011 09:55)

I was recently trying to loop through some objects and convert them to arrays so that I could encode them to json strings.

I was running into issues when an element of one of my objects was a SoapClient. As it turns out, json_encode() doesn't like any resources to be passed to it. My simple fix was to use is_resource() to determine whether or not the variable I was looking at was a resource.

I quickly realized that is_resource() returns false for two out of the 3 resources that are typically in a SoapClient object. If the resource type is 'Unknown' according to var_dump() and get_resource_type(), is_resource() doesn't think that the variable is a resource!

My work around for this was to use get_resource_type() instead of is_resource(), but that function throws an error if the variable you're checking isn't a resource.

So how are you supposed to know when a variable is a resource if is_resource() is unreliable, and get_resource_type() gives errors if you don't pass it a resource?

I ended up doing something like this:

<?php

function isResource ($possibleResource) { return !is_null(@get_resource_type($possibleResource)); }

?>

The @ operator suppresses the errors thrown by get_resource_type() so it returns null if $possibleResource isn't a resource.

I spent way too long trying to figure this stuff out, so I hope this comment helps someone out if they run into the same problem I did.

tacomage at NOSPAM dot devilishly-deviant dot net (07-Aug-2004 02:10)

Note that the use of is_resource isn't necessary in the example.  mysql_connect (along with any other function that would return a resouce, I imagine) returns false on failure, so the same results could be obtained with:
<?php

$db_link
= @mysql_connect('localhost', 'mysql_user', 'mysql_pass');
if (!
$db_link) {
   die(
'Can\'t connect : ' . mysql_error());
}

?>

Or even:
<?php
  $db_link
= @mysql_connect('localhost', 'mysql_user', 'mysql_pass')
  or die(
'Can\'t connect : ' . mysql_error());
}
?>

You'd be more likely to use is_resource AFTER the initial conection, to make sure the variable you intend to use as a resource is, in fact, a connection resource.  You might also use is_resource as a sanity-check prior to serializing an object, since resource variables can't be serialized.