Page 1 of 1

reference const definition dynamically

Posted: Fri Aug 24, 2007 8:19 am
by keenlearner
Hello, to keep things simple, let's say I have these,

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};

?>
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.

Posted: Fri Aug 24, 2007 8:50 am
by volka

Code: Select all

echo constant('myClass::'.$userInput);

Posted: Fri Aug 24, 2007 8:59 am
by xpgeek
Very intresting wich system do you develop?
Maybe we can help with best practice solution?

Posted: Fri Aug 24, 2007 9:16 am
by keenlearner
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.

Posted: Fri Aug 24, 2007 9:23 am
by volka
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)