Книга: Fedora™ Unleashed, 2008 edition

Variable Substitution

Variable Substitution

PHP allows you to use two methods to define strings: single quotation marks, double quotation marks, or heredoc notation, but the latter isn't often used. Single quotation marks and double quotation marks work identically, with one minor exception: variable substitution.

Consider the following code:

<?php
 $age = 25
 echo "You are ";
 echo $age;
?>

That is a particularly clumsy way to print a variable as part of a string. Fortunately, if you put a variable inside a string, PHP performs variable substitution, replacing the variable with its value. That means you can rewrite the code like so:

<?php
 $age = 25
 echo "You are $age";
?>

The output is the same. The difference between single quotation marks and double quotation marks is that single-quoted strings do not have their variables substituted. Here's an example:

<?php
 $age = 25
 echo "You are $age";
 echo 'You are $age';
?>

The first echo prints "You are 25", but the second one prints "You are $age".

Оглавление книги


Генерация: 1.172. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз