Request for Comments: Class casting to scalar
- Version: 1.0
- Date: 2008-11-24
- Author: Mark Karpeles <mark.at.hell.ne.jp>
- Status: Under Discussion
- First Published at: http://wiki.php.net/rfc/class_casting_to_scalar
This RFC covers a way to cast classes to scalar values other than strings.
Currently the Zend Engine provides some magic to methods in classes with defined names, for example __toString() is called when someone attempts to cast a class to a string.
The purpose of this RFC is to propose a way to allow casting to other scalar types (boolean, double, integer).
For the same reasons as __toString() exists, casting to other types might be needed. Feature requests have been submitted regarding this in the past.
Interface or magic method?
Currently two possibilities exists:
- Implementing a new magic method, for example __scalarValue() or __cast() in the Zend Engine.
- Creating a new interface (for example ScalarAccess?) and force the presence of one function (scalarValue()?) which will return the scalar value for this class.
Pass requested type?
Concern has been raised over the fact of passing the requested value type as parameter to the function, as it could be used to disallow some kinds of cast.
Proposal and Patch
- Patch for __cast() against PHP 5.2.6: http://ookoo.org/svn/snip/php-5.2.6_class_cast_func.patch
- Patch for __cast() against PHP 5.3.0: http://ookoo.org/svn/snip/php-5.3.0alpha2_class_cast_func.patch
- Extension for ScalarAccess interface for PHP 5.2.6: http://ookoo.org/svn/snip/phpcastable/
- None yet
- When used with math operators, it seems we *have* to cast to integer if not explictly requested in the code. TODO: find a way to force our way with a float value if needed
2008-11-24: Initial draft