haphpiness

These are things in PHP which make me genuinely_happy();

#[\NoDiscard] — Warn When Return Values Are Ignored

PHP 8.5 introduces the #[\NoDiscard] attribute, which tells the engine to emit a warning if the return value of a function or method is not used. It's essential for functions where ignoring the result is always a bug.

#[\NoDiscard("Validation result must be checked")]
function validate(array $data): ValidationResult {
    // ... returns success or failure with error messages
    return new ValidationResult($errors);
}

// This is almost certainly a bug — the result isn't checked
validate($formData);
// Warning: The return value of function validate() should either
// be used or intentionally ignored by casting it as (void)

// Correct usage
$result = validate($formData);
if ($result->hasErrors()) {
    return response($result->errors(), 422);
}

// Intentionally ignore with (void) cast
(void) validate($data);  // Explicit: "I know, I don't care"

// Perfect for immutable operations
readonly class Money {
    #[\NoDiscard]
    public function add(Money $other): self {
        return clone($this, ['amount' => $this->amount + $other->amount]);
    }
}

$price = new Money(100, 'USD');
$price->add(new Money(50, 'USD'));  // Warning! Result discarded — $price is immutable

This catches a category of bugs that static analyzers already flag but that the engine previously ignored: calling an immutable method and discarding the result, skipping a validation check, or dropping an error code.

Significance: API Safety

#[\NoDiscard] lets API authors encode an important constraint: "you must use this return value." It catches the classic bug of calling a method on an immutable object without capturing the new value — a mistake that silently produces wrong results.