From:
Operating system: Windows 7 Ultimate
PHP version: 5.3.8
Package: Class/Object related
Bug Type: Feature/Change Request
Bug description:Feature Request: __cast magic function
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 bug report at https://bugs.php.net/bug.php?id=55852&edit=1
--
Try a snapshot (PHP 5.4):
https://bugs.php.net/fix.php?id=55852&r=trysnapshot54
Try a snapshot (PHP 5.3):
https://bugs.php.net/fix.php?id=55852&r=trysnapshot53
Try a snapshot (trunk):
https://bugs.php.net/fix.php?id=55852&r=trysnapshottrunk
Fixed in SVN:
https://bugs.php.net/fix.php?id=55852&r=fixed
Fixed in SVN and need be documented:
https://bugs.php.net/fix.php?id=55852&r=needdocs
Fixed in release:
https://bugs.php.net/fix.php?id=55852&r=alreadyfixed
Need backtrace:
https://bugs.php.net/fix.php?id=55852&r=needtrace
Need Reproduce Script:
https://bugs.php.net/fix.php?id=55852&r=needscript
Try newer version:
https://bugs.php.net/fix.php?id=55852&r=oldversion
Not developer issue:
https://bugs.php.net/fix.php?id=55852&r=support
Expected behavior:
https://bugs.php.net/fix.php?id=55852&r=notwrong
Not enough info:
https://bugs.php.net/fix.php?id=55852&r=notenoughinfo
Submitted twice:
https://bugs.php.net/fix.php?id=55852&r=submittedtwice
register_globals:
https://bugs.php.net/fix.php?id=55852&r=globals
PHP 4 support discontinued:
https://bugs.php.net/fix.php?id=55852&r=php4
Daylight Savings: https://bugs.php.net/fix.php?id=55852&r=dst
IIS Stability:
https://bugs.php.net/fix.php?id=55852&r=isapi
Install GNU Sed:
https://bugs.php.net/fix.php?id=55852&r=gnused
Floating point limitations:
https://bugs.php.net/fix.php?id=55852&r=float
No Zend Extensions:
https://bugs.php.net/fix.php?id=55852&r=nozend
MySQL Configuration Error:
https://bugs.php.net/fix.php?id=55852&r=mysqlcfg