doumindang2416 2009-11-30 04:58
浏览 10
已采纳

根据其他变量值和静态文本构造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.

  • 写回答

3条回答 默认 最新

  • douyan1613 2009-11-30 05:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥30 数字信号处理实验报告
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要