note 103942 added to function.is-resource
| From: | btleffler | Date: | Thu, 12 May 2011 20:55:06 +0000 |
| Subject: | note 103942 added to function.is-resource | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-179667@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 69.147.83.197
Probable Submitter: 97.76.37.84
----
Manual Page -- http://www.php.net/manual/en/function.is-resource.php
Edit -- https://master.php.net/note/edit/103942
Del: integrated -- https://master.php.net/note/delete/103942/integrated
Del: useless -- https://master.php.net/note/delete/103942/useless
Del: bad code -- https://master.php.net/note/delete/103942/bad+code
Del: spam -- https://master.php.net/note/delete/103942/spam
Del: non-english -- https://master.php.net/note/delete/103942/non-english
Del: in docs -- https://master.php.net/note/delete/103942/in+docs
Del: other reasons-- https://master.php.net/note/delete/103942
Reject -- https://master.php.net/note/reject/103942
Search -- https://master.php.net/manage/user-notes.php