【问题标题】:How to implement the Countable interface in PHP?如何在 PHP 中实现 Countable 接口?
【发布时间】:2011-01-18 20:32:29
【问题描述】:

这样count($object)会返回其中的记录数

【问题讨论】:

    标签: php class interface count


    【解决方案1】:

    看看Countable::count

    class MyClass implements Countable {
        public function count() {
            //return count
        }
    }
    
    $c = new MyClass();
    count($c); //calls $c->count();
    

    【讨论】:

      【解决方案2】:

      如果你安装了标准 PHP 库,你应该能够简单地在你的类中实现 Countable,然后定义 count() 函数:

      class foo implements Countable {
          ...
          public function count() {
              # do stuff here
              return $count;
          }
      }
      

      在此处阅读有关 SPL 的更多信息: http://www.php.net/manual/en/book.spl.php

      这里有更多关于 Countable 接口的信息: http://php.net/manual/en/countable.count.php

      【讨论】:

        【解决方案3】:

        请注意,如果您的类是命名空间,则必须为 Countable 接口提供根命名空间:

        namespace App;
        
        class MyClass implements Countable {
            public function count() {
            //return count
            }
        }
        

        上面抛出错误:

        找不到接口“App\Countable”

        求解(注意Countable前面的斜线):

        namespace App;
        
        class MyClass implements \Countable {
            public function count() {
            //return count
            }
        }
        

        (仅供参考,不确定这是否是 Laravel 特有的,但我认为不是。)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-04-30
          • 2010-10-16
          • 2011-01-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多