This is an old revision of the document!
Request for Comments: Autoboxing
- Version: 1.0
- Date: 2010-05-04
- Author: Moriyoshi Koizumi moriyoshi@php.net
- Status: Under Discussion
- First Published at: http://wiki.php.net/rfc/autoboxing
- Other formats ..
Introduction
Autoboxing is a language feature that enables just-in-time conversion of a value object to another kind that is suitable to the context where it happens. In general, the source object is of a primitive data type like int or string, and the destination is an instance of a value class.
Why do we find it useful in PHP?
In PHP, unlike other scripting languages, there are fundamental differences between primitive types and classes. While they may contribute to a substantial boost of overall runtime performance, the differences prevent primitive values from having methods to operate with. For example, PHP has many functions named array_xxx() that operate on an array to produce a result in an immutable manner (doesn't modify the original data to store the result). They often look pretty much unintuitive when the operations are chained, because they don't allow one to write those operations in the order they occur, but to write them in a nested function calls where the innermost function gets called first.
Proposal
There would be a special function named __autobox()
that would be called whenever primitive types are used in a context where an object should occur, and expected to return an wrapper object that represents the value passed to it if the conversion is feasible, or null if not.
<?php function __autobox($value) { return ... /* some object */ } ?>
To enable autoboxing on integer value, one could write
<?php class IntObject { private $value; function __construct($value) { $this->value = $value; } function upTo($upper_bound) { return range($this->value, $upper_bound); } } function __autobox($value) { if (is_int($value)) { return new IntObject($value); } return null; } // Test code var_dump(1->upTo(10) == array(1, 2, 3, 4, 5, 6, 7, 8, 9)); ?>
Patch
A preliminary patch (may be a bit outdated) is available at http://gist.github.com/162517 .
Changelog
2008-10-13: initial version