JoJo
JoJo

Reputation: 20115

How to create static class constant variable from another constant variable?

I have a constant called PREFIX defined in constants.php. In class Foo, I would like to create a static class constant with PREFIX as the prefix. But I get a syntax error on that const definition line.

require_once 'constants.php';

class Foo {
    const FOO_CONST = PREFIX . 'bar';

    public function __construct() {
    }
}

Upvotes: 4

Views: 286

Answers (1)

user1252065
user1252065

Reputation:

In PHP a const must be a value, not an expression. So const FOO_CONST = 'foo' . 'bar'; won't work either.

You have to use define or a class member that gets initialized in the constructor instead of a const. Initializing a class member outside a class method with an expression does not work either.

Upvotes: 4

Related Questions