根据其他变量值和静态文本构造PHP变量名称
I want to tell my function which variable to call based on the day of the week. The day of the week is stored in $s_day, and the variables I want to call changes based on which day it is.
e.g.
I've stored a string 'Welcome to the week' in $d_monday_text1. Rather than build a set of 7 conditional statements (e.g. if date=monday echo $foo, else if date=tuesday echo $bar...), can I change the name of the variable called in the function by concatenating the name of the variable?
$s_day = date("l");
$text1 = '$d_'.$s_day.'_text1';
I'm hoping this evaluates to $d_monday_text1, which, as mentioned above, has the value "Welcome to the week". So, later on I'd want to use:
echo $text1;
To yield the resulting output = Welcome to the week.
I've looked into variable variables, which may be the way to go here, but am struggling with syntax. I can get it to echo the concatenated name, but I can't figure out how to get that name evaluated.
我想告诉我的函数根据星期几调用哪个变量。 一周中的某一天存储在$ s_day中,我想调用的变量根据它的日期而变化。 p>
例如 p>
I 已经在$ d_monday_text1中存储了一个字符串'Welcome to the week'。 而不是构建一组7个条件语句(例如,如果date = monday echo $ foo,否则如果date = tuesday echo $ bar ...),我可以通过连接名称来更改函数中调用的变量的名称吗? 变量? p>
$ s_day = date(“l”);
$ text1 ='$ d _'。$ s_day .'_ text1';
code>
我希望这个评估为$ d_monday_text1,如上所述,它具有“欢迎来到一周”的值。 所以,稍后我想使用: p>
echo $ text1;
code> pre>
产生结果 输出=欢迎来到这一周。 p>
我研究了变量变量,这可能是这里的方法,但我正在努力学习语法。 我可以让它回应连接的名称,但我无法弄清楚如何评估该名称。 p>
div>
Variable variables aren't a good idea - You should rather use arrays. They suit this problem much, much better.
For example, you could use something like this:
$messages = array(
'monday' => 'Welcome to the week',
'tuesday' => 'Blah blah',
'wednesday' => 'wed',
'thursday' => 'thu',
'friday' => 'fri',
'saturday' => 'sat',
'sunday' => 'week is over!'
);
$dayName = date('l');
echo $messages[$dayName];
Arrays are the data format used to store multiple related values such as these.
You can use this syntax:
$$text1
I've used this before. The evaluation comes as in:
$($text1)
Let's consider the following example:
$construction_no = 5;
$construction_5 = 'Door';
$var_name = 'construction_'.$construction_no;
$var_value = ${$var_name};
echo $var_value; //Door
Object oriented approach
$var_value = $this->{$var_name};
echo $var_value; //Door