Edit report at https://bugs.php.net/bug.php?id=55852&edit=1
ID: 55852 Updated by: sala...@php.net Reported by: hyponiq at gmail dot com Summary: Feature Request: __cast magic function -Status: Bogus +Status: Duplicate Type: Feature/Change Request Package: Class/Object related Operating System: Windows 7 Ultimate PHP Version: 5.3.8 Block user comment: N Private report: N New Comment: Duplicate of #46128 Previous Comments: ------------------------------------------------------------------------ [2011-10-05 11:28:45] johan...@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 10:35:26] 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 ?> ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=55852&edit=1