Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :))

like image 786
Anpan Avatar asked May 30 '13 14:05

Anpan


Video Answer


2 Answers

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");
    }
}
like image 193
Orangepill Avatar answered Oct 20 '22 23:10

Orangepill


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.

like image 1
deceze Avatar answered Oct 21 '22 00:10

deceze