Repository navigation
Description
Bug report
$this->prop ??= $cond ? A : B; is rewritten so that the ternary is parsed as ($this->prop ?? $cond) ? A : B. When the property is already set, its value is discarded and the result is A (the "true" branch) instead of the preset value. Plain PHP keeps the preset value.
Code snippet that reproduces the problem
<?php
declare(strict_types=1);
final class Button
{
public ?string $tooltip = null;
public string $direction = 'down';
public function init(): void
{
$this->tooltip ??= $this->direction === 'up' ? 'VALIDATE' : 'CANCEL';
}
}
$button = new Button();
$button->tooltip = 'Week tooltip';
$button->init();
echo "tooltip: ", $button->tooltip, "\n";Expected output
tooltip: Week tooltip
(Plain PHP, without TypePHP, prints exactly this: ??= only assigns when the property is null.)
Actual output
tooltip: VALIDATE
The transformed code shows why:
$this->tooltip = ($__typephpVal = \TypePHP\Internal\RuntimeTypeChecker::checkProperty($this->tooltip ?? $this->direction === 'up' ? 'VALIDATE' : 'CANCEL', $this, 'tooltip', __FILE__)) instanceof \TypePHP\Internal\Diagnostic\ErrorMessage ? throw ... : $__typephpVal;$this->tooltip ?? $this->direction === 'up' ? ... : ... is (($this->tooltip ?? $this->direction === 'up') ? ... : ...), because ?? binds tighter than ?:.
Notes
- Adding explicit parentheses around the ternary in the source (
??= ($cond ? A : B)) does not help: the parser drops them, the output is identical. - A right-hand side that binds tighter than
??(a plain value, a call,$a ?? $b) is not affected; I only hit it with a top-level ternary. - Likely related, unverified: other assign-ops that go through the same code path with a lower-precedence right-hand side. Only
??=with a ternary was tested.
Where it seems to come from
ContractVisitor::handleAssignOp() (src/Internal/Ast/ContractVisitor.php, around line 724) rebuilds the assign-op as new BinaryOp\Coalesce($var, $expr). The format-preserving printer (StreamWrapper printFormatPreserving, around line 309) then reuses the ternary's original tokens without re-adding parentheses, so the new Coalesce node prints its right operand unparenthesized. Wrapping the right operand (when it has lower precedence than ??) so the printer emits parentheses should fix it.
Versions
- TypePHP 0.11.6
- PHP 8.2.0 locally, PHP 8.5 (WebAssembly) in the playground: both print
tooltip: VALIDATE.
Context
One occurrence in a production codebase (a lazily-initialised tooltip: $this->tooltip ??= $this->direction === 'up' ? ... : ...); the preset value was silently replaced.
Activity
rcalicdan commentedon Nov 20, 2026
Thank you for this bug report.. This will be resolved on next patch release.
If you encounter more problem, don't hesitate to submit more issue.
rcalicdan commentedon Nov 22, 2026
@fdaviddpt Hello this is now fixed on recent v0.14.1
I'm happy to announce that this release brings massive performance improvement..