php Laravel:找出变量是否是集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34619145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: find out if variable is collection
提问by Albert
I want to find out if a variable is a collection.
我想知道一个变量是否是一个集合。
I can't use is_object() because it will be true even if it is not an collection. For now I use this, and it works:
我不能使用 is_object() 因为即使它不是一个集合它也会是真的。现在我使用它,它有效:
if(is_object($images) && get_class($images) != 'Illuminate\Database\Eloquent\Collection') {
But I think it's so ugly that I spend time asking you about another solution.
但我认为它太丑了,以至于我花时间向您询问另一种解决方案。
Do you have any idea?
你有什么主意吗?
回答by P. Gearman
Couldn't you use
你不能用吗
if(is_a($images, 'Illuminate\Database\Eloquent\Collection')) {
....do whatever for a collection....
} else {
....do whatever for not a collection....
}
Or
或者
if ($images instanceof Illuminate\Database\Eloquent\Collection) {
}
回答by Konchog
The class being used is incorrect here. In a general sense, you should be testing for the base class.
这里使用的类不正确。一般来说,您应该测试基类。
use Illuminate\Support\Collection;
....
if($images instanceof Collection) {
....
}
回答by insitderp
Just wanted to correct an error I ran into on this answer.
只是想纠正我在这个答案中遇到的错误。
Note that instanceof
excepts either a (obj) or the name of the class without quotes
请注意,instanceof
a (obj) 或不带引号的类名除外
$images instanceof Illuminate\Database\Eloquent\Collection
Also, interestingly enough there is a speed/performance difference using instanceof
over is_a
, but this is probably not relevant for you if you are like me and were searching for an answer to this question in the first place.
此外,有趣的是,使用instanceof
over存在速度/性能差异is_a
,但是如果您像我一样并且首先正在寻找这个问题的答案,这可能与您无关。
回答by Naveed Khan
For me using is_countable worked:
对我来说使用 is_countable 工作:
if(is_countable($somethingCountable)) {
// do something with array
} else {
// print something else
}
}