laravel 如何检查某物是否可数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42899605/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:36:44  来源:igfitidea点击:

How to check if something is countable?

phparrayslaravellaravel-collection

提问by rap-2-h

I have a var: $a. I don't know what it is. I want to check if I can count it. Usually, with only array, I can do this:

我有一个 var: $a。我不知道那是什么。我想看看我能不能数出来。通常,只有数组,我可以这样做:

if (is_array($a)) {
    echo count($a);
}

But some other things are countable. Let's say a Illuminate\Support\Collectionis countable with Laravel:

但其他一些事情是可数的。假设Illuminate\Support\Collection在 Laravel 中a是可数的:

if ($a instanceof \Illuminate\Support\Collection) {
    echo count($a);
}

But is there something to do both thing in one (and maybe work with some other countable instances). Something like:

但是,是否可以将两件事合二为一(并且可能与其他一些可数实例一起使用)。就像是:

if (is_countable($a)) {
    echo count($a);
}

Does this kind of function exists? Did I miss something?

有这种功能吗?我错过了什么?

回答by Brian Leishman

For previous PHP versions, you can use this

对于以前的 PHP 版本,您可以使用这个

if (is_array($foo) || $foo instanceof Countable) {
    return count($foo);
}

or you could also implement a sort of polyfill for that like this

或者你也可以像这样实现一种 polyfill

if (!function_exists('is_countable')) {

    function is_countable($c) {
        return is_array($c) || $c instanceof Countable;
    }

}


Note that this polyfill isn't something that I came up with, but rather pulled directly from the RFC for the new function proposal https://wiki.php.net/rfc/is-countable

请注意,这个 polyfill 不是我想出来的,而是直接从 RFC 中提取的新功能提案https://wiki.php.net/rfc/is-countable

回答by rap-2-h

PHP 7.3

PHP 7.3

According to the documentation, You can use is_countablefunction:

根据文档,您可以使用is_countable功能:

if (is_countable($a)) {
    echo count($a);
}