Initializing PHP class property declarations with simple expressions yields syntax error

PHP doesn’t do such operations at compile-time; you cannot assign calculated values to constants, even if all operators are constants themselves. Default values of class members are treated the exact same way. I encountered this behaviour as I tried to assign powers of two to constants:

class User {
    const IS_ADMIN = 1;
    const IS_MODERATOR1 = 1 << 1; // Won't work
    const IS_MODERATOR2 = 0x02;   // works
}

Leave a Comment