|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #69486 Add support foir _toBoolean magic method
Submitted: 2015-04-20 08:02 UTC Modified: 2021-08-19 15:05 UTC
From: adrian at adecsys dot com Assigned: cmb (profile)
Status: Wont fix Package: Class/Object related
PHP Version: 5.4.40 OS: *
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: adrian at adecsys dot com
New email:
PHP Version: OS:


 [2015-04-20 08:02 UTC] adrian at adecsys dot com
From manual page:

The inbuilt conversion of objects to Boolean, especially for expression evaluation, is poor and could be greatly improved.

I propose one of two mechanisms:

(a) Given the existing __toString() magic method, use this as an intermediate step in the conversion to a bool value, following the documented rules for string.

(b) add support for an explicit __toBoolean magic method, which allows the implentation to take full control over the resulting type.

Thank you

Test script:
class NullObject {
  public function __toString() { return ""; }
  public function __toBoolean() { return false; }
  public function __call($name , $arguments) { return $this; }

$test = new NullObject();
echo $test ? "TRUE" : "FALSE" ;

// TRUE, but logically expect FALSE


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2015-04-20 08:49 UTC]
-Package: PHP Language Specification +Package: Class/Object related
 [2015-04-27 23:02 UTC]
-Operating System: CentOS/WinXP +Operating System: *
 [2015-04-27 23:02 UTC]
Proposal A would constitute a BC break, though. Consider existing
code relying on boolean type juggling (or a cast) to test for
object existence, where the object has a __toString method
returning a "falsy" value (like in the given test script).

With regard to proposal B: how is int (or float) juggling, for
instance, supposed to work?

  (int) $obj->__toString()
  (int) $obj->__toBoolean()
  (int) $obj
 [2021-08-19 15:05 UTC]
-Status: Open +Status: Wont fix -Assigned To: +Assigned To: cmb
 [2021-08-19 15:05 UTC]
Seems there is not much interest in this feature, and given that
the details have not been figured out, I'm closing this as

Anybody who is looking for a ::__toBoolean() magic method or
something like this, is welcome to pursue the RFC process[1].

[1] <>
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Thu Sep 16 16:03:37 2021 UTC