===== Request for Comments: Scalar Type Casting Magic Methods ===== * Version: 0.2 * Date: 2012-03-03 * Author: Anthony Ferrara * Maintainer: Matiss Treinis * Status: In Draft (Inactive) * Patch: https://gist.github.com/1966809 ===== Introduction ===== Currently, the Zend Engine exposes several methods to PECL extensions and internal classes to control how internal objects behave when casting to primitives. The two methods used in this RFC are specifically ''cast_object()'' and ''get()'' . This proposal is to expose those two methods as a series of 5 new magic methods to allow user classes to hook into this functionality more completely. ===== Use Cases ===== ==== Scalar Wrapping ==== One use-case for this functionality is in creating wrapper classes for scalar values. There are several possibilities that this will enable: * Creating strict-typing functionality with entirely user-land code (having a variable that until unset cannot be assigned to with anything except an integer for example) * Having object code be compatible with existing scalar-typed code. An example would be SplFixedArray would be enabled to be passed to any function (including internal functions) that expect arrays which are not passed by reference. * Allows for objects to carry a Boolean state (to be truthy and falsy) ===== Implementation ===== ==== Syntax ==== This RFC and patch introduces 4 new magic methods: * ''_ _toInt()'' - Called when casting an object explicitly to an integer (or passing it to an internal function which expects an integer) * ''_ _toFloat()'' - Called when casting an object explicitly to a float (or passing it to an internal function which expects a float) * ''_ _toArray()'' - Called when casting an object explicitly to an array (or passing it to an internal function which expects an array) * ''_ _toScalar()'' - Called when using an object in an implicit scalar scope without type information (for example: ''$obj + 1''). * ''_ _toBool()'' - Called when casting an object explicitly to a boolean (or passing it to an internal function which expects a boolean) ==== Handler Behavior ==== When the cast_object handler is called, the type parameter is switched against to determine which magic method to call. The four possibilities include ''toInt()'', ''toFloat()'', ''toArray()'', ''toString()'' and ''toBool()''. When the get handler is called, the ''toScalar()'' method is invoked. This would indicate that the cast is to a scalar, but the type is up to the class to determine. This is called when a primitive type is needed, but not a specific one. So the normal math operators trigger a get call: (+, -, *, /), in addition to compound operators (++, +=, &=, |=, etc). ==== Example Triggers ====