2

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.

  1. __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 with ArrayAccess?
  2. 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

Josh Bruce
  • 1,002
  • 13
  • 24
  • 2
    `echo $foo ? 'true' : 'false';` doesn't cut it? – ceejayoz Jul 06 '20 at 00:53
  • 1
    [Contributing to PHP - Feature requests](https://github.com/php/php-src/blob/master/CONTRIBUTING.md#feature-requests) – Phil Jul 06 '20 at 01:16
  • Hey @Phil - I don't agree with the closure and have added to the question. Thank you for the link. – Josh Bruce Jul 06 '20 at 02:59
  • @ceejayoz - See clarification on question. I hope it doesn't actually add to the confusion. – Josh Bruce Jul 06 '20 at 03:00
  • @Phil - ps. I just realize the link goes to instructions on submitting an RFC, which I mentioned probably wouldn't work given my limited knowledge of PHP internals and C. Please let me know if I should submit a further reframed question - as apparently it was not obvious what I was asking, which is not a duplicate of the reference question. Thanks. – Josh Bruce Jul 06 '20 at 03:05
  • 1
    @JoshBruce I see. Re-opened – Phil Jul 06 '20 at 03:24
  • Thanks for clarifying. I'd think the PHP way of doing this would be to have something like `if($instance->isValid()) { ... }`. – ceejayoz Jul 07 '20 at 01:35
  • Agreed. That seems to be the only way at present. I'm putting together a potential RFC - gauging interest right now (more clarification there as the goal is to give another way for custom objects to be treated like native PHP): https://github.com/joshbruce/external-project-proposals/blob/master/php-concepts/interact-with-instance-as-php.md – Josh Bruce Jul 09 '20 at 14:02

0 Answers0