Search code examples
phpoopcoding-style

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

  • In Java and other languages this is a commonly used way to namespace constants to avoid naming collisions. See here;

    The way that I would implement such a class is like this"

    // make this final so no one can extend it
    final class Errors{
        const SUCCESS = 0;
        const BAD_ARGUMENT = -1;
        const BAD_QUERY = -2;
        const OUT_OF_MANA = -3;
    
        // make this private so noone can make one
        private function __construct(){
            // throw an exception if someone can get in here (I'm paranoid)
            throw new Exception("Can't get an instance of Errors");
        }
    }