How to concatenate a variable in the middle of another variable?

Asked

Viewed 58 times

1

I would like to make the content of a variable form another variable, for example:

$name = 'clientes';
$default_$name_list = "Lista de clientes";

I want to make the default variable $default_clientes_list, there is some way to do this in PHP?

3 answers

4


You can get to something similar using variable variables in PHP.

$name = 'clientes';
$lista_var = "default_{$name}_list";
$$lista_var = "Lista de clientes";

echo $default_clientes_list;

Behold working.

Or even simplifying a little more without assigning to the intermediate variable.

$name = 'clientes';
${"default_{$name}_list"} = "Lista de clientes";

echo $default_clientes_list;

In my opinion, I do not recommend following this line. This greatly impairs the readability of the code without having an apparent benefit. Only makes it more complex and difficult for those who will read the code.

  • Good answer. Just to reinforce that this practice is ma, I add another point to what you have already said. It is also possible to replace values of other local variables that exist with the generated name, without the person noticing, creating bugs that are difficult to detect. Small example

3

Look I don’t know if this you can do, but you can do in array.

For example:

$name="clientes";
$defaultList['clientes']= "Lista de clientes";
$defaultList['representantes'] = "Lista de representantes";

and then you pull what you want:

echo $defaultList[$name]; // Lista de clientes;

1

In your example it doesn’t work because PHP is looking for the variable $name_list, that doesn’t exist.

To get the effect you want, I think it would be this way.

$varName = sprintf("default_%s_list", $name /* ou 'clientes' */);
$$varName = /* você terá uma variável $default_clientes_list com o valor que passar aqui */;

However I do not recommend this practice either. In this case and in several others similar I believe it is better to use Arrays.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.