'PHP Classes containing only constants

First of all: I tried to google it, but I mostly only found discussions about how to define arrays in constants and other unrelated information.

I have a question regarding a solution to make my code more readable (and pretty) that just occured to me. Basically I have most functions return a status code that indicates success or, in case something went wrong, an error code. For this, I made a class called "StatusCode" that contains only constants, like so:

<?php
class StatusCode {
  const success = 0;
  const badArgument = -1;
  const badQuery = -2;
  const outOfMana = -3; //Really just for demonstration purposes
  ...
}

The purpose is to make magic numbers disappear from my code and make it clear what went wrong without having to look for an explaination somewhere:

if (mana > 10) {
  //Do some magic
  return StatusCode::success;
}
else {
  //Oh god this is not good!
  return StatusCode::outOfMana;
}

It should also eliminate the possibility of accidently using duplicate error codes. I'm pretty sure this adds a minor overhead to my application, but has made my code easier to understand in return. Is there some earth shattering reason not to do this? Maybe an even better way to go about it?

(I have avoided the define(CONSTANT, "value") approach because it seems less pretty and it's a hassle to write on my German keyboard :))



Solution 1:[1]

This has the advantage of namespacing and grouping constants. You can use reflection on that class to iterate over defined constants, which allows you, for example, to validate that a value is a value of a certain constant group (enabling a poor man's constant type hinting).

The disadvantage is that you're kind of abusing a class (though only slightly). Purists may not like that. Constants which are not used in the same class should be global constants; you can even namespace them into something like \StatusCodes\SUCCESS in PHP 5.3+.

The choice is yours, really.

Solution 2:[2]

Creating an static class will solve your problem and avoid creating multiple instances of StatusCode

Namespaces can be used if you think your application can have multiple StatusCode classes but still the StatusCode will be static.

If you want to use singleton pattern this will work too

Choice is yours!

Solution 3:[3]

You can use an interface, so an instance cannot be created:

interface StatusCode {
    public const success = 0;
    public const badArgument = -1;
    public const badQuery = -2;
    public const outOfMana = -3;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 deceze
Solution 2 Waqar Alamgir
Solution 3 Steve Bauman