Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cast In Const

PHP accepts the cast operators in constant expressions. Until then, operators such as (int), (float), (string), (array) were not allowed.

While using a cast on a literal value is rather meaningless, static constant expressions may be build on top of other constants.

Then, (object) is still not accepted, along with (void).

PHP code

<?php

const S = 123s;
const C = (int) S;

class X {
    const C = (int) S;
}

echo C;

?>

Before

PHP Fatal error:  Constant expression contains invalid operations

Fatal error: Constant expression contains invalid operations

After

123

PHP version change

This behavior changed in 8.5.

Error Messages

Extension

© 2023-2026, Damien Seguy - Exakat