Reputation: 10818
I am using a third party logging library and there is a line where it runs substr()
in a loop. There is an if (!is_array($value))
around it, but it seems like $value
can wind up being pretty much any type of variable. A few weeks ago we had to put in a pull request to add !is_object($value)
to the if statement because a different library was causing $value
to be an object. And now we just ran into a situation where $value
is a Resource.
So I thought this exclusionary tactic may not be maintainable, why not just do:
if (is_string($value){ substr($value,0,3);...
That doesn't work, though, because sometimes $value
is an int
which can be used in substr()
with no complaints.
so is if (is_string($value) || is_int($value) )
sufficient? How can I properly check if a variable is "stringable".
Because this code is running inside the app, but logging things outside of the app, we really don't want it throwing exceptions that would not bring the app down otherwise, or hide the reason the app is failing
Upvotes: 0
Views: 96
Reputation: 5700
Objects can only be cast if they have the magic __toString()
method. Everything else can be cast to a string, but may or may not be useful.
"Array"
"Resource id #..."
null
and false
are converted to the empty string (""
)true
is converted to the string "1"
More information on this is here at official documentation.
One option for dealing with values that either won't cast or don't cast to anything useful is to use var_export($value, true)
, serialize($value)
or one of the other serialize functions built in to PHP.
Refer var_export and serialize on official documentation for complete information.
Upvotes: 1