PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
<?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};
?>
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.
Thanks Volka, it works, I got a question, how do you knows that if there is a function for such a kind of usage when you never came across the function, by checking in the php.net ? If so how can I check ? Thanks.
Hello, xpgeek, I am actually using the LexerGenerator and ParserGenerator from PEAR package you can search for it pear.php.net . Where Parser has a list of defined constant that identifies the token terminal symbols, whereas the Lexer will use the predefined constant from Parser to assign it into the $this->token of Lexer's class.
keenlearner wrote:I got a question, how do you knows that if there is a function for such a kind of usage when you never came across the function, by checking in the php.net ? If so how can I check ? Thanks.
In this case: no idea
imho http://de2.php.net/language.oop5.constants should contain a note about constant() and class constants.
(constant() is mentioned in the user contributed notes though)