I'm going to ask two questions, as I'm pretty sure the answer to the first is "No, you can't" or a derivative.
__toString()
let's us tell PHP how to treat an instance in situations where a string is presumed (ex.print()
). I have not been able to locate the ability to that for booleans (ex.if ($instance) {}
). Is there something like this? Even an interface like withArrayAccess
?- If there's not, how does one submit a request to PHP - despite not knowing enough about PHP internals or C to suggest a way to implement it? (So, probably not a full RFC.)
To hopefully be more clear:
class MyClass
{
public function __toString()
{
return "Hello, World!";
}
// What I'm very sure doesn't exist but wish did,
// even via an interface and not a magic method.
public function __toBool()
{
return false;
}
}
$instance = new MyClass();
print $instance; // Hello, World!
if ($instance) {
print "valid instance is always true";
}
$cast = (bool) $instance;
print ($cast) ? "true" : "false"; // should be false. but is true
The primary question is not how to convert a bool to a string. Instead maybe it would be better to phrase it as how to tell PHP what to do when casting an instance of my class to a bool
(??).
[UPDATE]: See and discuss RFC - https://wiki.php.net/rfc/objects-can-be-falsifiable