Thursday, December 22, 2022

[FIXED] What does ${ } mean in PHP syntax?

Issue

I have used PHP for a long time, but I just saw something like,

${  } 

To be precise, I saw this in a PHP Mongo page:

$m = new Mongo("mongodb://${username}:${password}@host");

So, what does ${ } do? It is quite hard to search with Google or in the PHP documentation for characters like $, { and }.


Solution

${ } (dollar sign curly bracket) is known as Simple syntax.

It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

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";

echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
?>

The above example will output:

He drank some apple juice.
He drank some juice made of .
He drank some juice made of apples.


Answered By - celiker
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.