reference const definition dynamically
Posted: Fri Aug 24, 2007 8:19 am
Hello, to keep things simple, let's say I have these,
So is there an alternative way to solve my problem of without using switch statement ? The myClass has to have constant definition. In contrast, not using variable. Thanks.
Code: Select all
<?php
class myClass
{
const CONST_VAR1 = 1;
const CONST_VAR2 = 2;
//.....until
const CONST_VAR1000 = 1000;
}
//let's say user knows the name from CONST_VAR1 to CONST_VAR1000
//so if user input CONST_VAR1 we should print out the define value
echo myClass::CONST_VAR1; // output 1
//I can use switch statment to refer to the defined constant value in myClass
$userInput = 'CONST_VAR1000';
switch($userInput)
{
case 'CONST_VAR1':
echo myClass::CONST_VAR1;
break;
case 'CONST_VAR2':
echo myClass::CONST_VAR2;
break;
//....until
case 'CONST_VAR1000':
echo myClass::CONST_VAR1000;
break;
}
//but instead of writing such a long switch statements, can we refer to the defined constant dynamically ?
//I have tried out this but is an error
echo myClass::{$userInput};
?>