Raja Gopal Raja Gopal - 2 months ago 69
PHP Question

PHP Error : Fatal error: Constant expression contains invalid operations

I searched for this already here in SO which has similar headings still I can't figure whats happening. Kindly pardon me if this looks silly or simple as I am just learner.

I am getting an error:

Fatal error: Constant expression contains invalid operations in
config.php on line 214

That line was:

protected static $dbname = 'mydb_'.$appdata['id'];

Whether I did any mistakes in quotes? Or somewhere else?

Kindly help me please.


From the official Php documentation :

Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.

So you cannot initialize a static variable with another variable. Replace $appdata['id'] by a constant string or remove the static attribute.

This is because static declarations are resolved in compile-time, when the content of other variables is not know (see this other page of official doc).