I have a PHP site which uses language system based on "define" method. For example:
define("_question_1", "How old are you?"); define("_question_2", "Question 2?"); define("_question_3", "Question 3?"); .... define("_question_10", "Question 10?");
I have 5-10 questions I need to ask. And I need to select what question I want to ask. So I make a query to my DB. Something like:
SELECT q_title FROM questions_db WHERE id=3 OR id=10;
Database returns two TEXT(!) values:
_question_3, _question_10
Which I save to:
$a = _question_3; $b = _question_10;
Next thing I need is to show the text of the description defined earlier. When I use _question_3 as VARIABLE it works like this:
echo ""._question_3.""; //returns "Question 3?"
But I have only _question_3 as TEXT value and it's works like this:
echo "".$a.""; //returns "_question_3"
THE QUESTION: How to convert text value to PHP variable and make something like?
define("_question_3", "Question 3?");
$a = _question_3; //text value
//do something with $a....
echo "".$a.""; //returns "Question 3?"
Thanks for help. PS Please change the title if it doesn't clear to understanding.
只需使用constant()
即可将变量值用作常量,例如
echo constant($a);
In PHP you could use variable variable – dynamic variable names.
$a = '_question_3'; $b = 'Question 3?'; $$a = $b; echo $b; // prints "Question 3?" echo $_question_3; // prints "Question 3?"
But it's not good solution. Try not to use dynamic variable names.
May be associative array will be more suitable to you?
$questions = []; // Creating an empty array $questions['_question_3']['question'] = 'Question 3?'; // Storing a question $questions['_question_3']['answers'] = [ // Adding answers 'Answer 1', 'Answer 2', 'Answer 3' ];
Or declare a Question
class and create instances of it.
class Question { public $Question; public $Answers; __construct($question, $answers) { $this->Question = $question; $this->Answers = $answers; } } $q1 = new Question('Question 1?', ['Answer 1', 'Answer 2', 'Answer 3']);
Try constant() it returns the value of a constant, for example:
var_dump(constant('YourConstantNameHere'));
or with variables
var_dump(constant($a));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.