Pergunta

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 ?

Foi útil?

Solução

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

Outras dicas

In other languages, this will work because the compiler will recognize mathematical expressions that contain only constant literals, and "reduce" them to a single constant literal value... thus, most "simple" mathematical expressions are allowed in contexts where actual code is not allowed to exist.

In php, however, there is no compiler (at least not in the traditional sense). PHP is interpreted. So, many "compile time" features that we're used to having in other languages, simply don't exist in PHP.

This is one of those cases. Unless you want to move your constants into a class (instead of an interface) and make them static member variables (instead of constants), you're stuck doing the math yourself:

(16 & 32 & 64 & 128) == 0

though, I suspect you actually meant:

(16 | 32 | 64 | 128) == 240
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top