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?
你有什么主意吗?
3 个解决方案
#1
22
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) {
}
#2
7
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) {
....
}
#3
4
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会有速度/性能差异,但如果你像我一样并且首先在寻找这个问题的答案,这可能与你无关。
#1
22
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) {
}
#2
7
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) {
....
}
#3
4
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会有速度/性能差异,但如果你像我一样并且首先在寻找这个问题的答案,这可能与你无关。