What is the Countable interface for in PHP?

Asked

Viewed 166 times

6

I saw a certain class whose statement was that way:

class Collection implements Countable {}

I realized she was implementing Countable, but I didn’t understand what this implementation was doing there.

What is the purpose of Countable? This is a standard PHP interface?

2 answers

5


Yeah, it’s a standard interface PHP. Serves to make an object compatible with the function count(). If your class implements Countable and has a method count, this method will be invoked when a class instance is passed to the function count global PHP.

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

4

According to the documentation is to force the implementation of the method Count(). It is used in classes of data collections that need to standardize to obtain the count of all items contained in it.

In general, it is expected that the complexity is O(1), but it is not required, and for this the most adopted strategy is to keep the count of the object in some member and any change in it is already reflected in this counter.

Each class can implement the mechanism as long as the interface-compliant API.

  • My example then was not good, because it is O(n) -- I think.

  • @bfavaretto ideally is not good at all, but does not prevent to use. As I said can do as you see fit. Only that normal, in decent languages :D is expected to the programmer to do O(1), but is not required.

  • I switched my example to an O(1 implementation) :-)

  • @bfavaretto actually don’t know if that way is O(N), I think she does the same as you are doing. I may be wrong, but all that count() of the language accepted to count must have the count stored

  • Capable indeed. But considering the "good practices" you mentioned, I thought it best to leave an example that takes care of its own count.

  • I had forgotten the +1 :p

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.