根据其他变量值和静态文本构造一个PHP变量名称 [英] Construct a PHP variable name based on other variable values and static text
问题描述
我想告诉我的函数根据星期几来调用哪个变量.星期几存储在$ s_day中,我要调用的变量根据它是哪一天而改变.
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.
例如
我在$ d_monday_text1中存储了一个字符串"Welcome to the week".除了建立7条条件语句的集合(例如,如果date = monday echo $ foo,否则如果date = tuesday echo $ bar ...),我可以通过串联函数名来更改函数中调用的变量的名称吗?变量?
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';
我希望它的计算结果为$ d_monday_text1,如上所述,其值为"Welcome to the week".因此,稍后我想使用:
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.
推荐答案
变量不是一个好主意-您应该使用数组.他们非常好地解决了这个问题.
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.
这篇关于根据其他变量值和静态文本构造一个PHP变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!