How does {$ variable} work in PHP?

When I want to use the value of a variable inside a string, I bind them to. (point).

I see that some people use {$ variable} inside a string.

So ... my example:

"my name is ".$variable 

some people use it:

 "my name is {$variable}" 

What is the difference between the two examples?

+4
source share
2 answers

Used when you want to add a string to a variable value inside a string.

 $variable = 'hack'; // now I want to append 'ed' to $variable: echo "my name is {$variable}"; // prints my name is hack echo "my name is {$variable}ed"; // prints my name is hacked echo "my name is $variable"; // prints my name is hack echo "my name is $variableed"; // Variable $variableed not defined. 
+11
source

Perhaps some examples will explain the brackets and. operator for string concatenation.

Suppose you have a variable holding a certain value, which means $ money, and you want to display this amount.

 $money=10; print "you have earned $money"; // would output 'you have earned 10; // ops missed the dollar sign as we are dealing with currency. print "you have earned $$money"; // hmmm, that wont work $$ means something else. 

So, if you have curly braces, you can tell PHP which variable you want to replace in the string is much clearer.

 print "you have earned ${$money}.00"; would now output 'you have earned $10.00' 

Now it looks a lot nicer.

+2
source

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


All Articles