Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement the Countable interface in PHP?

So that count($object) will return the number of records in it

like image 236
user198729 Avatar asked Feb 19 '10 16:02

user198729


2 Answers

Take a look at Countable::count

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

$c = new MyClass();
count($c); //calls $c->count();
like image 192
Yacoby Avatar answered Sep 24 '22 21:09

Yacoby


If you have Standard PHP Library installed you should be able to simply implement Countable in your class and then define the count() function:

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

Read more about the SPL here: http://www.php.net/manual/en/book.spl.php

More about the Countable interface here: http://php.net/manual/en/countable.count.php

like image 21
thetaiko Avatar answered Sep 22 '22 21:09

thetaiko