This is an old revision of the document!
PHP RFC: Internal operator overloading and GMP improvements
- Version: 0.1
- Date: 2013-05-12
- Author: Nikita Popov nikic@php.net
- Status: Draft
- Target version: PHP 5.6 (or whatever the next one is)
Introduction
PHP offers facilities for large number and decimal arithmetic (GMP and BCMath), but currently using those is a PITA. This RFC proposes to improve the situation by adding support for operator overloading in internal classes. Furthermore this RFC exemplarily implements the new API for GMP (and improves GMP in various ways along the way).
TODO: More motivation!
Proposal A: Operator overloading
The operator overloading is implemented by adding a new object handler do_operation
with the following signature:
typedef int (*zend_object_do_operation_t)(zend_uchar opcode, zval *result, zval *op1, zval *op2 TSRMLS_DC);
Here opcode
is the opcode of the operation (e.g. ZEND_ADD
), result
is the target zval, op1
the first operand and op2
the second operand. For binary operations both operands are used, for unary operations the second operand is NULL
. The return value can be either SUCCESS
or FAILURE
. If FAILURE
is returned then the code falls back to the default behavior for the respective operator.
The following opcode
values are supported:
+ ZEND_ADD - ZEND_SUB * ZEND_MUL / ZEND_DIV % ZEND_MOD << ZEND_SL >> ZEND_SR . ZEND_CONCAT | ZEND_BW_OR & ZEND_BW_AND ^ ZEND_BW_XOR xor ZEND_BOOL_XOR ~ ZEND_BW_NOT (unary) ! ZEND_BOOL_NOT (unary) == ZEND_IS_EQUAL != ZEND_IS_NOT_EQUAL < ZEND_IS_SMALLER <= ZEND_IS_SMALLER_OR_EQUAL
The operators >
, >=
, unary +
and unary -
are indirectly supported by the following compiler transformations:
$a > $b ==> $b < $a $a >= $b ==> $b <= $a +$a ==> 0 + $a -$a ==> 0 - $a
The compound assignment operators +=
, -=
, *=
, /=
, %=
, <<=
, >>=
, .=
, |=
, &=
and ^=
are supported by the runtime transformation $a op= $b => $a = $a op $b
.
The prefix operators ++
and --
are supported by the runtime transformations ++$a => $a = $a + 1
and --$b => $b = $b - 1
. The same applies for the corresponding postfix operators, with the difference that a copy of the old value is returned (rather than the newly computed value).