Skip to content
Advertisement

PHP: Class constants in type declarations of input paramaters

For a custom logger I want to force the caller to pass a valid class constant defined in PsrLogLogLevel.

This class is defined like:

JavaScript

The loggers’ function (wrong) looks like:

JavaScript

This does not work because LogLevel::DEBUG for instance is a string and not an instance of the class. Is there any way to enforce a class constant in a PHP type declaration? Because if I define string then you can pass any string obviously, but I just want to allow the declared constants.

Advertisement

Answer

PHP doesn’t have constant restrictions, only types.

But you can do a workaround like this:

JavaScript

Now your static funcion works

JavaScript

$logLevel will receive LogLevel::emergency(), LogLevel::critical(), etc. and you can get the level name just calling $logLevel->getName()

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement