Overload the behavior of count() when called on certain objects
Posted
by
Tom
on Stack Overflow
See other posts from Stack Overflow
or by Tom
Published on 2011-12-14T18:52:00Z
Indexed on
2012/09/03
9:38 UTC
Read the original article
Hit count: 127
In PHP 5, you can use magic methods, overload some classes, etc. In C++, you can implement functions that exist is STL 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.
© Stack Overflow or respective owner