Gurnzbot
Gurnzbot

Reputation: 4132

PHP constant() referencing another class's constant

Within a class of mine I have a variable that contains a constant that is declared in another library class I'm using.

I am attempting to use it as such:

constant($colour)

Where $colour = PHPExcel_Style_Color::COLOUR_YELLOW

PHP logs are throwing errors such as:

PHP Warning: constant(): Couldn't find constant PHPExcel_Style_Color::COLOUR_YELLOW

If I were straight up use the constant instead of a variable it'd work fine. PHPExcel_Style_Color::COLOUR_YELLOW

Any reason why I would be seeing this error using the constant() function with a variable?

Upvotes: 1

Views: 54

Answers (1)

samanime
samanime

Reputation: 26527

If you are using it within a namespace, you'll need an absolute namespace.

$colour = 'PHPExcel_Style_Color::COLOUR_YELLOW' is relative.

If PHPExcel_Style_Color is the top level namespace for that, then you probably just need to add a slash \ at the beginning of it.

Try this:

constant('\' . $colour);

which will make the overall path:

\PHPExcel_Style_Color::COLOUR_YELLOW

Without the slash, it's equivalent to:

MyNamespace\PHPExcel_Style_Color::COLOUR_YELLOW

Upvotes: 1

Related Questions