1

My question is why do we use the php bracing. Take for example :

let say I want to echo out something like this Now date and time is <23-07-15 00:02:45>

$dateNtimeToday=date('d-m-y H:i:s');

$dateNtime="Now date and time is <{$dateNtimeToday}>";

OR

$dateNtime="Now date and time is  <".$dateNtimeToday.">";

OR

$dateNtime="Now date and time is <$dateNtimeToday>";  

in any of these cases

echo $dateNtime;

I am just wondering what is the differences and implications

1 Answer 1

3

The short answer is this: embedding variables in strings using the "brace" syntax you refer to is usually easier to read and understand than a bunch of concatenation.

Wrapping braces around the variable name helps PHP determine exactly where the variable name starts and stops within the string, so it doesn't get mixed up with literal characters around it.

Here's an example straight from the docs about why this can be an issue:

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<?php
$juice = "apple";

//This will work as expected
echo "He drank some juice made of {$juice}s.";

//Doesn't work due to the trailing 's'
//PHP thinks you're trying to use a variable called $juices, which doesn't exist
echo "He drank some juice made of $juices.";

Read more: http://php.net/manual/en/language.types.string.php#language.types.string.parsing

Sign up to request clarification or add additional context in comments.

3 Comments

i cant understand your answer . as you have not make use of the brace in your example and explanation of PHP_EOL
Try: echo "He drank some juice made of {$juice}s."; See if that clarifies
I apologize, I used the example straight from the docs. @Rasclatt's example is probably better and I will update my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.