Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining class constant in PHP

Tags:

php

constants

I would like to define a class constant using a concatenation of an existing constant and a string. I can't predefine it because only scalars are allowed for predefining constants, so I currently have it as part of my constructor with a defined() function checking if it is already defined. This solution works but my constant is now unnecessarily global.

Is there a way to define a class constant at runtime in php?

Thank you.

like image 527
joshs Avatar asked Feb 24 '10 22:02

joshs


1 Answers

See the PHP manual on Class constants

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

In other words, it is not possible. You could do it with runkit_constant_add but this sort of monkey patching is strongly discouraged.

like image 156
Gordon Avatar answered Sep 22 '22 06:09

Gordon