4

For general constants, Coding standards / Naming Conventions says that constants should always be all-uppercase, with underscores to separate words and that module-defined constant names should also be prefixed by the module module machine name, all-uppercase, and an underscore character.

Object-oriented names don't follow the normal conventions of prefixing the name with the module or using underscores; instead, they opt for various forms of camel case.

Unfortunately, Object-oriented code doesn't mention class constants at all.

Which of the following is correct?

  • const FOO_CONSTANT_VALUE = 'bar';
  • const CONSTANT_VALUE = 'bar';
  • const constantValue = 'bar';

2 Answers 2

3

The correct one would be:

class Foo {
  const CONSTANT_VALUE = 'bar';
}

For example, quoting after Zend Framework naming conventions (however there are many others for different frameworks, just Google around):

Constants may contain both alphanumeric characters and underscores. Numbers are permitted in constant names.

All letters used in a constant name must be capitalized, while all words in a constant name must be separated by underscore characters.

For example, EMBED_SUPPRESS_EMBED_EXCEPTION is permitted but EMBED_SUPPRESSEMBEDEXCEPTION is not.

Constants must be defined as class members with the "const" modifier. Defining constants in the global scope with the "define" function is permitted but strongly discouraged.

It does not explicitely say anything about FOO_CONSTANT_VALUE vs CONSTANT_VALUE, but not using class name in constant name is general practice. Which perfectly makes sense, considering that you are in class scope.

0
1

What reported from the Drupal coding standards about constants is still valid for constants defined in classes. The only difference is that constants defined from a class don't need any prefix that identify the module that defines the constants; that prefix would be eventually added to the class name.

There isn't the need to add a prefix that is derived from the class name to the constant name, as Foo::CONSTANT_NAME is different from Bar::CONSTANT_NAME, and PHP will not throw an error when both the constants are defined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.