Construct a PHP variable name based on other varia

2019-01-28 12:10发布

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.

3条回答
霸刀☆藐视天下
2楼-- · 2019-01-28 12:16

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 
查看更多
一纸荒年 Trace。
3楼-- · 2019-01-28 12:19

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.

查看更多
我只想做你的唯一
4楼-- · 2019-01-28 12:35

You can use this syntax:

$$text1

I've used this before. The evaluation comes as in:

$($text1)

查看更多
登录 后发表回答