Greetings All,
Intro
=====
The discussion over type hinting seems to be getting divided between
those who really like it (most likely the ones who write strongly typed
programs anyway) and those who don't want to add yet another kind of
type system to PHP.
I have been thinking about it and wondered why we don't borrow a concept
from C# with a PHP twist of course. The basic idea of boxing in C# is
that a value type is implicitly converted to an object type. Unboxing is
done explicitly to convert the object back to a value type.
Idea
====
I figure instead of adding scalar type hints, we could reuse the object
type hints to do implicit boxing of variables. Either (but not both) a
new magic method (``__box`` for example) or a new interface (``Boxable``
for example) would need to be added to PHP. The method would accept the
scalar value and set its internal representation (similar to
``__wakeup``). The method could either (but not both) return false or
throw an exception (``BoxingException`` for example).
It is my belief that PHP would need to include as many object versions
of scalar types as possible. The boxing functionality could be added to
the SPL Types [1]_ to provide for standard representations of the scalar
types. However the power to box variables would also be available in
userland classes.
The unboxing of variables would need to occur on an explicit cast or on
a call to an internal function. The unboxing could be implemented as the
RFC for class casting to scalar [2]_. It already discusses some examples
for a new magic method or interface. I propose some more to relate to
the unboxing concept (``__unbox`` for a magic method, and ``Unboxable``
for an interface).
Benefits
========
The benefits to boxing and unboxing include:
- Only minor modifications required to the current type-hinting
implementation (I am only assuming this part).
- The boxing and unboxing ability can be used in userland classes
to accomplish "cool things".
- Get SplTypes and scalar casting in PHP core.
- Probably more that I can't think of off the top of my head.
Patch
=====
I have very limited C skills, so no patch exists.
.. [1] `SPL Types <http://.php.net/manual/en/book.spl-types.php>`_
.. [2] `RFC: Class casting to scalar
<http://wiki.php.net/rfc/class_casting_to_scalar`_
Thanks,
--
Joshua Thompson
Mechanical Engineer/Software Developer
http://www.schmalls.com
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php