检查项目是否可以转换为字符串?
我正在写一个调试方法。
我
if(is_xxx($item)){
//echo output info for type
}
最后想做的是
if(can_be_string($item))
echo $item;
是否有 can_be_string
类型的函数?
I am writing a debug method.
What I have is
if(is_xxx($item)){
//echo output info for type
}
what I want to do at the end is
if(can_be_string($item))
echo $item;
Is there a can_be_string
type function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
为了完成...
http://www.php.net/is_scalar,自 PHP 4 起可用;对此只字不提..:)
For the sake of completion...
http://www.php.net/is_scalar, available since PHP 4; not a single word about it.. :)
好的,已编辑,合并了 Michiel Pater 的建议(现在答案已消失)和 @eisberg 的建议。不管怎样,
settype
都会返回true
对象,就像看起来的那样。Ok, edited, with incorporating Michiel Pater's suggestion (who's answer is gone now) ans @eisberg's suggestions.
settype
will returntrue
with objects no matter what, as it seems.怎么样
,从 PHP 8 开始,您可以用
$var instanceof Stringable
替换第三个条件How about
And since PHP 8 you can replace the third condition with
$var instanceof Stringable
通过测试快速而肮脏地实现:
Quick and dirty implementation with test:
这是我能找到的最短方法:
Here is the shortest way I can find:
这个决定怎么样?
how about this decision?
非常简单:
代码已经过测试。
如果
$var
不是对象,则method_exists()
函数返回false
,因此不需要进行此验证。It's very simple:
The code has already been tested.
The
method_exists()
function returnsfalse
if$var
is not an object, so this verification is not necessary.如果IS_STRING()无帮助,那么我只能提出一些想法:
If is_string() doesn't help you, then I can only suggest some ideas:
我认为所有答案都不令人满意。
最简单的实现:
I didn't think any of the answers were satisfactory.
Simplest implementation: