What is the interface for Countable in PHP?

3

I saw a certain class whose declaration was this way:

class Collection implements Countable {}

I noticed that she was implementing Countable , but I did not understand what that implementation was doing there.

What is the purpose of Countable ? Is this a default PHP interface?

    
asked by anonymous 07.10.2016 / 20:09

2 answers

2

Yes, it's a default interface of PHP. Serves to make an object compatible with count() . If your class implements Countable and has a count method, this method is invoked when an instance of the class is passed to the count global PHP function.

For example:

<?php
class Lista implements Countable {

    private $items = [];
    private $total = 0;

    public function add($item) {
        array_push($this->items, $item);
        $this->total++;
    }

    public function count() {
        return $this->total;
    }
}

$lista = new Lista();
$lista->add(1);
$lista->add('foo');

var_dump(count($lista)); // 2
    
07.10.2016 / 20:18
3

According to documentation is to enforce the Count() method implementation. It is used in data collection classes that need a standardized way to get the count of all items contained in it. In general, it is expected that complexity is O (1), for this the most adopted strategy is to save the count of the object in some member and any changes in it already be reflected in that counter. Each class can implement the engine as long as the API complies with the interface.

    
07.10.2016 / 20:17