Lately I've been in the habit of assigning integer values to constants and simply using the constant name as a means of identifying its purpose. However, in some cases this has resulted in the need to write a function like typeToString($const) when a string representation is needed. Obviously this is inefficient and unneccesary, but is only an issue every once and a while.
So my question is, are there any other tradeoffs I should consider? Which case is considered to be cleaner/more standards-compliant? Also, is the performance difference negligable for most cases?
Case 1: (faster when a string version is not needed?)
class Foo {
const USER_TYPE_ADMIN = 0;
const USER_TYPE_USER = 1;
const USER_TYPE_GUEST = 2;
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
public function typeToString() {
switch($this->userType) {
case self::USER_TYPE_ADMIN:
return 'admin';
break;
case self::USER_TYPE_USER:
return 'user';
break;
case self::USER_TYPE_GUEST:
return 'guest';
break;
default:
return 'unknown';
break;
}
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->typeToString();
// Displays "guest"
Case 2:(faster/easier when a string version is needed)
class Foo {
const USER_TYPE_ADMIN = 'admin';
const USER_TYPE_USER = 'user';
const USER_TYPE_GUEST = 'guest';
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->userType();
// Displays "guest"