[英]How can I concatenate a constant and a variable and store it in a class constant with PHP?
[英]How can I use the value of a variable as constant?
我有一個PHP網站,該網站使用基於“定義”方法的語言系統。 例如:
define("_question_1", "How old are you?"); define("_question_2", "Question 2?"); define("_question_3", "Question 3?"); .... define("_question_10", "Question 10?");
我有5-10個問題要問。 我需要選擇我要問的問題。 因此,我向數據庫進行查詢。 就像是:
SELECT q_title FROM questions_db WHERE id=3 OR id=10;
數據庫返回兩個TEXT(!)值:
_question_3, _question_10
我保存到:
$a = _question_3; $b = _question_10;
接下來,我需要顯示前面定義的描述文本。 當我使用_question_3作為VARIABLE時,它的工作方式如下:
echo ""._question_3.""; //returns "Question 3?"
但是我只有_question_3作為TEXT值,它的工作方式如下:
echo "".$a.""; //returns "_question_3"
問題:如何將文本值轉換為PHP變量並使之類似?
define("_question_3", "Question 3?");
$a = _question_3; //text value
//do something with $a....
echo "".$a.""; //returns "Question 3?"
感謝幫助。 附言:如果不清楚,請更改標題。
只需使用constant()
即可將變量值用作常量,例如
echo constant($a);
在PHP中,您可以使用變量變量–動態變量名。
$a = '_question_3'; $b = 'Question 3?'; $$a = $b; echo $b; // prints "Question 3?" echo $_question_3; // prints "Question 3?"
但這不是一個好的解決方案。 盡量不要使用動態變量名。
可能關聯數組會更適合您嗎?
$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' ];
或聲明一個Question
類並創建它的實例。
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']);
嘗試constant(),它返回常量的值,例如:
var_dump(constant('YourConstantNameHere'));
或帶有變量
var_dump(constant($a));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.