Question

I'm trying to figure out the proper naming convention for class constants.

For general constants, the coding standards states:

Constants should always be all-uppercase, with underscores to separate words. This includes pre-defined PHP constants like TRUE, FALSE, and NULL. Module-defined constant names should also be prefixed by an uppercase spelling of the module they are defined by.

However, object-oriented names don't follow the normal conventions of prefixing the name with the module or using underscores, instead opting for various forms of camel case. And unfortunately, the object-oriented coding standards doesn't mention class constants at all.

So which of the following is correct?

class Foo {
  const FOO_CONSTANT_VALUE = 'bar';
}

or

class Foo {
  const CONSTANT_VALUE = 'bar';
}

or

class Foo {
  const constantValue = 'bar';
}
Was it helpful?

Solution

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.

OTHER TIPS

What reported from the Drupal coding standards about constants is still valid for constants defined in classes. The only difference is that a constant defined from a class don't need any prefix that identify the module defining it; 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top