String Interpolation
String interpolation in PHP allows you to include variable values directly within a string. This is primarily done using double-quoted strings and Heredoc syntax. Here are examples of how to use string interpolation in PHP:
Using Double-Quoted Strings
When you use double quotes, PHP will parse the string and replace any variables with their values.
<?php
$name = "John";
$age = 25;
// Simple interpolation
$greeting = "Hello, $name!";
echo $greeting; // Outputs: Hello, John!
// More complex interpolation
$info = "My name is $name and I am $age years old.";
echo $info; // Outputs: My name is John and I am 25 years old.
// Interpolating array values
$user = ['name' => 'Alice', 'age' => 30];
echo "User's name is {$user['name']} and age is {$user['age']}.";
// Outputs: User's name is Alice and age is 30.
?>
Using Curly Braces for Clarity
When embedding complex variables or arrays, it’s often clearer to use curly braces to delimit the variable names.
<?php
$name = "John";
$age = 25;
// Using curly braces for complex expressions
$greeting = "Hello, {$name}!";
$info = "My name is {$name} and I am {$age} years old.";
echo $greeting; // Outputs: Hello, John!
echo $info; // Outputs: My name is John and I am 25 years old.
?>
Using Heredoc Syntax
Heredoc syntax allows for multiline string interpolation and is particularly useful for embedding large blocks of text or code.
<?php
$name = "John";
$age = 25;
$heredocString = <<<EOD
Hello, $name!
You are $age years old.
This is a multiline string using Heredoc syntax.
EOD;
echo $heredocString;
// Outputs:
// Hello, John!
// You are 25 years old.
// This is a multiline string using Heredoc syntax.
?>
Interpolation with Object Properties
If you have an object, you can also interpolate its properties within strings.
<?php
class User {
public $name = "John";
public $age = 25;
}
$user = new User();
echo "User's name is $user->name and age is $user->age.";
// Outputs: User's name is John and age is 25.
?>
Interpolating Results of Function Calls
You can also interpolate the results of function calls directly in a string.
<?php
function getName() {
return "John";
}
echo "Hello, " . getName() . "!"; // Outputs: Hello, John!
echo "Hello, {getName()}!"; // Will not work as PHP does not support function calls inside string interpolation.
?>
In summary, string interpolation in PHP using double-quoted strings and Heredoc syntax is a powerful way to embed variable values directly within strings, making your code cleaner and more readable.