|
| 1 | +--TEST-- |
| 2 | +Readonly scalar property arithmetic preserves native operands, checked reads and evaluation order |
| 3 | +--FILE-- |
| 4 | +<?php |
| 5 | +final class ReadonlyArithmeticBox |
| 6 | +{ |
| 7 | + public function __construct( |
| 8 | + public readonly float $width, |
| 9 | + public readonly float $height, |
| 10 | + public readonly int $count, |
| 11 | + public readonly bool $enabled, |
| 12 | + ) {} |
| 13 | + |
| 14 | + public function ratio(): float { return $this->width / $this->height; } |
| 15 | +} |
| 16 | + |
| 17 | +final class UninitializedReadonlyArithmeticBox |
| 18 | +{ |
| 19 | + public readonly float $width; |
| 20 | +} |
| 21 | + |
| 22 | +function halfReadonlyBox(ReadonlyArithmeticBox $box): float |
| 23 | +{ |
| 24 | + return $box->width < $box->height ? $box->width / 2.0 : $box->height / 2.0; |
| 25 | +} |
| 26 | + |
| 27 | +function nextReadonlyCount(ReadonlyArithmeticBox $box): int { return $box->count + 1; } |
| 28 | +function readonlyEnabled(ReadonlyArithmeticBox $box): bool { return $box->enabled === true; } |
| 29 | +function readonlyReceiver(ReadonlyArithmeticBox $box): ReadonlyArithmeticBox { echo "receiver\n"; return $box; } |
| 30 | +function readonlyDivisor(): float { echo "divisor\n"; return 2.0; } |
| 31 | +function orderedReadonlyHalf(ReadonlyArithmeticBox $box): float |
| 32 | +{ |
| 33 | + return readonlyReceiver($box)->width / readonlyDivisor(); |
| 34 | +} |
| 35 | +function uninitializedReadonlyHalf(UninitializedReadonlyArithmeticBox $box): float { return $box->width / 2.0; } |
| 36 | +function nullableReadonlyHalf(?ReadonlyArithmeticBox $box): float { return $box->width / 2.0; } |
| 37 | + |
| 38 | +function main(): void |
| 39 | +{ |
| 40 | + $box = new ReadonlyArithmeticBox(6.0, 12.0, 4, true); |
| 41 | + var_dump(halfReadonlyBox($box), $box->ratio(), nextReadonlyCount($box), readonlyEnabled($box)); |
| 42 | + var_dump(halfReadonlyBox(new ReadonlyArithmeticBox(12.0, 6.0, 0, false))); |
| 43 | + var_dump(readonlyEnabled(new ReadonlyArithmeticBox(1.0, 2.0, 0, false))); |
| 44 | + var_dump(orderedReadonlyHalf($box)); |
| 45 | + try { |
| 46 | + uninitializedReadonlyHalf(new UninitializedReadonlyArithmeticBox()); |
| 47 | + } catch (Error $error) { |
| 48 | + echo "uninitialized: ", $error->getMessage(), "\n"; |
| 49 | + } |
| 50 | + try { |
| 51 | + nullableReadonlyHalf(null); |
| 52 | + } catch (Error $error) { |
| 53 | + echo "null receiver\n"; |
| 54 | + } |
| 55 | +} |
| 56 | +?> |
| 57 | +--EXPECT-- |
| 58 | +float(3) |
| 59 | +float(0.5) |
| 60 | +int(5) |
| 61 | +bool(true) |
| 62 | +float(3) |
| 63 | +bool(false) |
| 64 | +receiver |
| 65 | +divisor |
| 66 | +float(3) |
| 67 | +uninitialized: Typed property UninitializedReadonlyArithmeticBox::$width must not be accessed before initialization |
| 68 | +null receiver |
0 commit comments