Build a PHP variable name based on other variable values ​​and static text

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 vary depending on what day it is on.

eg.

I saved the line "Welcome to the week" in $ d_monday_text1. Instead of creating a set of 7 conditional statements (for example, if date = monday echo $ foo, else if date = tuesday echo $ bar ...), can I change the name of the variable called in the function by combining the variable name?

$s_day = date("l"); $text1 = '$d_'.$s_day.'_text1'; 

I hope this evaluates to $ d_monday_text1, which, as mentioned above, has a value of "Welcome for a week." So later I would like to use:

 echo $text1; 

To get the final result = Welcome for a week.

I looked at the variable variables that might be here, but I'm struggling with the syntax. I can make his echo concatenate the name, but I cannot figure out how to get that name.

+3
source share
3 answers

Variables are not a good idea. You must use arrays. They approach this problem much, much better.

For example, you can 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 a data format used to store several related values, such as.

+9
source

You can use this syntax:

$$ text1

I have used this before. The assessment is as follows:

$ ($ text1)

+3
source

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 
0
source

Source: https://habr.com/ru/post/1389111/


All Articles