php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #55852 Feature Request: __cast magic function
Submitted: 2011-10-05 10:35 UTC Modified: 2011-10-05 13:22 UTC
From: hyponiq at gmail dot com Assigned:
Status: Duplicate Package: Class/Object related
PHP Version: 5.3.8 OS: Windows 7 Ultimate
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: hyponiq at gmail dot com
New email:
PHP Version: OS:

 

 [2011-10-05 10:35 UTC] hyponiq at gmail dot com
Description:
------------
I think it'd be a useful tool to add a __cast($to) magic function to the Classes and Objects category of PHP syntax. What said function would do is allow the programmer to specify the return values of casting a user-land object into one of the built-in data types. I.E. using (int) MyObject would invoke the __cast() method passing it the 'int' type. In such a case, the programmer could then specify what is returned when cast to, per se, int's.

<?php
class MyObject {
    public $myValue = null;
    public function __construct($value) {
        $this->myValue = $value;
    }
    
    public function __cast($to = 'string') {
        switch ($to) {
            case 'string':
                return 'The value of myValue is: ' . (string) $this->myValue;
            case 'int':
                return strlen($this->myValue);
        }
    }
}

$myObject = new MyObject('I am a string');
print (int) $myObject; // Output: 13
?>


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2011-10-05 11:28 UTC] johannes@php.net
-Status: Open +Status: Bogus
 [2011-10-05 11:28 UTC] johannes@php.net
This is not possible as there are too many places where it isn't cleatr which types should be used.

Let
   $a = new Object();
   $b = new Object();
Where
   Object implements your __cast() method
Then do
   $c = $a + $b;
What type should be requested? - The + operator can work with integers, floats and arays.

Or do
   $d = str_replace($a, $b, "some text");
what should be used then? - str_replace can work on strings and arrays.

We have __toString for everything else use specific methids.
    $e = $a->toInt() + $b->toInt();
 [2011-10-05 13:22 UTC] salathe@php.net
-Status: Bogus +Status: Duplicate
 [2011-10-05 13:22 UTC] salathe@php.net
Duplicate of #46128
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sun Jul 13 23:01:33 2025 UTC