phpoverloadingcountable

Overload the behavior of count() when called on certain objects


Possible Duplicate:
Count elements for objects implementing ArrayAccess using count()?

In PHP 5, you can use magic methods, overload some classes, etc. In C++, you can implement functions that exist as long as the argument types are different. Is there a way to do this in PHP?

An example of what I'd like to do is this:

class a {
    function a() {
        $this->list = array("1", "2");
    }
}

$blah = new a();

count($blah);

I would like blah to return 2. IE count the values of a specific array in the class. So in C++, the way I would do this might look like this:

int count(a varName) { return count(varName->list); }

Basically, I am trying to simplify data calls for a large application so I can call do this:

count($object);

rather than

count($object->list);

The list is going to be potentially a list of objects so depending on how it's used, it could be really nasty statement if someone has to do it the current way:

count($object->list[0]->list[0]->list);

So, can I make something similar to this:

function count(a $object) {
    count($object->list);
}

I know PHP's count accepts a mixed var, so I don't know if I can override an individual type.


Solution

  • It sounds like you want to implement the Countable interface:

    class a implements Countable {
        public function __construct() {
            $this->list = array("1", "2");
        }
    
        public function count() {
          return count($this->list);
        }
    }
    
    $blah = new a();
    
    echo count($blah); // 2