I am creating a collection class and would like it to be drop-in-replacement for arrays, which I use currently.
How to create a class which could be casted to boolean, so the class can be truthy or falsy?
A simple test shows that an object of empty class is truthy:
class boolClass {}
$obj = new boolClass();
var_dump( (bool)$obj);
//prints
//bool(true)
But I need to decide if my class is truthy or falsy. Is there eny way to tell the PHP engine how to cast my class to boolean? Like I could do with __toString()?
Background:
Lets say I write a class like this (it’s an example only):
class MyCollection implements ArrayAccess, Iterator {
//...
}
I heavily use this patterns currently:
$var = array();
if (empty($var)) {
//array is empty, (or there is no array at all)
// I do something here
}
I would like that to look like:
$var = new MyCollection(array());
and keep the rest unchanged. But the $var containing MyCollection is always truthy so I would need to all the conditions to:
if ($var->isEmpty()) {
//...
}
But this is unacceptable, as my codebase have many megabytes.
Any solution here?
On this page, the magic methods that you can define for your classes are enumerated.
http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring
You demonstrate that you already know about
__toString().Unfortunately, there is no magic method listed there that does what you are asking. So, I think for now your only option is to define a method and call that method explicitly.