php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #70604 Magic Integer casting + NULL cast
Submitted: 2015-09-30 08:47 UTC Modified: 2016-08-07 04:54 UTC
From: jodminster at gmx dot net Assigned:
Status: Suspended Package: *General Issues
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: jodminster at gmx dot net
New email:
PHP Version: OS:

 

 [2015-09-30 08:47 UTC] jodminster at gmx dot net
Description:
------------
Analog to __toString() a __toInt() method.

Additionally allow NULL as a valid return value for casting methods.

Test script:
---------------
class test {
   private $value;
   function __construct($value = null) {
        $this->value = $value;
   }
   function __toString() {
      return $this->value ? (string) $this->value : $this->value;
   }
   function __toInt() {
     return $this->value ? (int) $this->value : $this->value;
   }
}

(string)(new test()) === null;
(string)(new test('1')) === '1';
(string)(new test(1)) === '1';
(int)(new test()) === null;
(int)(new test('1') === 1;
(int)(new test(1) === 1;


Expected result:
----------------
6 x true

Actual result:
--------------
* Catchable fatal error: Method test::__toString() must return a string value in php shell code on line 1

*__toInt is never called

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-08-06 02:31 UTC] kalle@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: kalle
 [2016-08-06 02:31 UTC] kalle@php.net
This issue have been brought up multiple times to allow overloading for casting objects to other times besides string.

I suggest you to mail to internals@ and perhaps write an RFC about this, as it will bring more attention to the feature.

Thanks for helping to make PHP even greater!
 [2016-08-06 09:36 UTC] nikic@php.net
-Status: Closed +Status: Suspended
 [2016-08-07 04:54 UTC] kalle@php.net
-Assigned To: kalle +Assigned To:
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 03 11:01:34 2025 UTC