Search code examples
phpclass-structuredynamic-values

Assigning dynamic values with variables / constants in classes


Iv'e always been aware that you cannot set dynamic values to variables within a class structure, but is there any way around this?

I have this interface:

interface IUserPermissions
{
    /*
        * Public VIEW,CREATE,UPDATE,DELETE
    */
    const PUBLIC_VIEW   = 1;
    const PUBLIC_CREATE = 2;
    const PUBLIC_EDIT   = 4;
    const PUBLIC_DELETE = 8;
    const PUBLIC_GLOBAL = 1 | 2 | 4 | 8;          #Section 1

    /*
        * Admin  VIEW,CREATE,UPDATE,DELETE
    */
    const ADMIN_VIEW    = 16;
    const ADMIN_CREATE  = 32;
    const ADMIN_EDIT    = 64;
    const ADMIN_DELETE  = 128;
    const ADMIN_GLOBAL  = 16 | 32 | 64 | 128;     #Section 2
}

Within this code the lines marked as Section 1 & 2 trigger an error, More specific the error is below:

syntax error, unexpected '|', expecting ',' or ';'

But as this is an interface there's no method there is no code blocks allowed.

Can anyone offer a solution ?


Solution

  • You can't use these operators in class member declarations. However, you can simply perform the math yourself and assign the result. Since 1 | 2 | 4 | 8 and 16 | 32 | 64 | 128 evaluate to 15 and 240, respectively, just do:

    const PUBLIC_GLOBAL = 15; // 1 | 2 | 4 | 8
    

    and

    const ADMIN_GLOBAL  = 240; // 16 | 32 | 64 | 128