Next: , Previous: , Up: Overloading Operators   [Contents]


4.2 Binary Assignment Operators

SyntaxInstruction
$a += $bZEND_ASSIGN_ADD
$a -= $bZEND_ASSIGN_SUB
$a *= $bZEND_ASSIGN_MUL
$a /= $bZEND_ASSIGN_DIV
$a %= $bZEND_ASSIGN_MOD
$a **= $bZEND_ASSIGN_POW
$a <<= $bZEND_ASSIGN_SL
$a >>= $bZEND_ASSIGN_SR
$a .= $bZEND_ASSIGN_CONCAT
$a |= $bZEND_ASSIGN_BW_OR
$a &= $bZEND_ASSIGN_BW_AND
$a ^= $bZEND_ASSIGN_BW_XOR
$a = $bZEND_ASSIGN
$a =& $bZEND_ASSIGN_REF

Binary assignment operators behaves similar to non-assignment binary operators, with the exception that it should not generate a result when it is not used (opline->result_type == IS_UNUSED). When you overload these operators, make sure that you never touch the result zval under such circumstances.

The execution result of a binary assignment operator is expected to replace the first operand. However, it is not mandatory and is not done automatically by the Zend Engine.

Code example:

int
assign_add_handler(
    zend_execute_data *execute_data
) {
    return op_handler(execute_data, [] (auto zv1, auto zv2, auto rv) {
        if (Z_TYPE_P(zv1) == IS_OBJECT) {
            // ... handle addition.
            __update_value(Z_OBJ_P(zv1), add_result);
            if (rv != nullptr) {
                ZVAL_COPY(rv, zv1);
            }
            return true;
        }
        return false;
    });
}