Inserting php vars directly into a string

One way to insert a php var into a string is with concatenation, like so:

echo "Welcome ".$name."!"

This is pretty clunky though, so I use the following way to insert the var directly into the string:

echo "Welcome $name!"

However, the quick-and-easy way without concatenation won’t work some times. When you need to insert a property two objects deep ($this->address->name), or have a letter right after a var name (Welcome $names), php will get confused. So, you need to use {}.

echo "Welcome {$this->address->name}!"

Leave a Reply