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"
You use a CONSTANT when you know a value will never be changed. You use a variable when you want a value to be changed. You should use constants if you want to ensure that the value will not/cannot get changed anywhere after it's been defined.
The basic difference between these two is that const defines constants at compile time, whereas define() defines them at run time. We can't use the const keyword to declare constant in conditional blocks, while with define() we can achieve that.
The performance difference will be negligible unless you're storing a lot of them.
I'd write the toString()
method more concisely:
$strings = array
(
self::USER_TYPE_ADMIN => 'admin',
self::USER_TYPE_USER => 'user',
);
if (!isset($strings[$type]))
return 'unknown';
return $strings[$type];
Also, you could make the $strings
array a static
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With