I'll answer according to the PHP manual , A literal string type can be specified in four different ways:
To not extend much, let's see the first two to your question.
Simple quotation marks
The simplest way to declare a string is by using single quotes (the% character '
).
Note: Unlike double quotation syntax ""
and heredoc <<<EOD
, variables
and escape statements for special characters will not be expanded when included within a string in single quotes ''
.
Example:
<?php
echo 'Esto es una cadena sencilla';
echo 'También se pueden incluir nuevas líneas en
un string de esta forma, ya que es
correcto hacerlo así';
// Resultado: Arnold una vez dijo: "I'll be back"
echo 'Arnold una vez dijo: "I\'ll be back"';
// Resultado: Ha borrado C:\*.*?
echo 'Ha borrado C:\*.*?';
// Resultado: Ha borrado C:\*.*?
echo 'Ha borrado C:\*.*?';
// Resultado: Esto no se expandirá: \n una nueva línea
echo 'Esto no se expandirá: \n una nueva línea';
// Resultado: Las variables $tampoco se $expandirán
echo 'Las variables $tampoco se $expandirán';
?>
Double quotes
If a string is formed with double quotes ("), PHP will interpret the following escape sequences as special characters:
Escape characters:
+-------------+------------------------------------------------------+
| Secuencia | Significado |
+-------------+------------------------------------------------------+
| \n | avance de línea (LF o 0x0A (10) en ASCII) |
+-------------+------------------------------------------------------+
| \r | retorno de carro (CR o 0x0D (13) en ASCII) |
+-------------+------------------------------------------------------+
| \t | tabulador horizontal (HT o 0x09 (9) en ASCII) |
+-------------+------------------------------------------------------+
| \v | tabulador vertical (VT o 0x0B (11) en ASCII) |
| | (desde PHP 5.2.5) |
+-------------+------------------------------------------------------+
| \e | escape (ESC o 0x1B (27) en ASCII) |
| | (desde PHP 5.4.4) |
+-------------+------------------------------------------------------+
| \f | avance de página (FF o 0x0C (12) en ASCII) |
| | (desde PHP 5.2.5) |
+-------------+------------------------------------------------------+
| \ | barra invertida |
+-------------+------------------------------------------------------+
| \$ | signo de dólar |
+-------------+------------------------------------------------------+
| \" | comillas dobles |
+-------------+------------------------------------------------------+
| \[0-7]{1,3} | la secuencia de caracteres que coincida con la |
| | expresión regular es un carácter en notación octal,|
| | que silenciosamente desborda para encajar en un |
| | byte (p.ej. "0" === "<?php
$jugo = "manzana";
echo "Él tomó algo de jugo de $jugo.".PHP_EOL;
// Inválido. "s" es un carácter válido para un nombre de variable, pero la variable es $jugo.
echo "Él tomó algo de jugo hecho de $jugos.";
// Válido. Explícitamente especifica el final del nombre de la variable encerrándolo entre llaves:
echo "Él tomó algo de jugo hecho de ${jugo}s."
?>
0") |
+-------------+------------------------------------------------------+
| \x[0-9A-Fa- | la secuencia de caracteres que coincida con la |
| f]{1,2} | expresión regular es un carácter en notación |
| | hexadecimal |
+-------------+------------------------------------------------------+
| \u{[0-9A-Fa | la secuencia de caracteres que coincida con la |
| -f]+} | expresión regular es un punto de código de Unicode,|
| | la cual será imprimida al string como dicha |
| | representación UTF-8 del punto de código (añadido |
| | en PHP 7.0.0) |
+-------------+------------------------------------------------------+
Note: The most important feature of double quoting ""
of a string is the fact that the names of the variables are expanded.
Variable analysis
When a string is specified by double quotes ""
or by heredoc <<<EOT
, the variables within that string will be analyzed.
There are two types of syntax: a simple and a complex . The simple syntax is the most used and practical. Provides a way to embed a variable
, a value of array
or a property of a object
within a cadena
with minimum effort.
Complex syntax can be recognized by the braces that delimit the expression.
Simple syntax
If a dollar sign is found ( $
), the parser will take the largest number of symbols to form a valid variable name. Delimiting the variable name with braces allows explicitly specifying the end of the name.
Example:
Él tomó algo de jugo de manzana.
Él tomó algo de jugo hecho de .
Él tomó algo de jugo hecho de manzanas.
The result of the example would be:
$jugos = array("manzana", "naranja", "koolaid1" => "púrpura");
echo "Él tomó algo de jugo de $jugos[0].".PHP_EOL;
echo "Él tomó algo de jugo de $jugos[1].".PHP_EOL;
echo "Él tomó algo de jugo $jugos[koolaid1].".PHP_EOL;
class persona {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";
public $smith = "Smith";
}
$persona = new persona();
echo "$persona->john tomó algo de jugo de $jugos[0].".PHP_EOL;
echo "$persona->john entonces dijo hola a $persona->jane.".PHP_EOL;
echo "La esposa de $persona->john saludó a $persona->robert.".PHP_EOL;
echo "$persona->robert saludó a los dos $persona->smiths."; // No funcionará
Similarly, you can analyze the index of a array
or the property of a object
.
Él tomó algo de jugo de manzana.
Él tomó algo de jugo de naranja.
Él tomó algo de jugo púrpura.
John Smith tomó algo de jugo de manzana.
John Smith entonces dijo hola a Jane Smith.
La esposa de John Smith saludó a Robert Paulsen.
Robert Paulsen saludó a los dos .
The result of the example would be:
<?php
// Mostrar todos los errores
error_reporting(E_ALL);
$genial = 'fantástico';
// No funciona, muestra: Esto es { fantástico}
echo "Esto es { $genial}";
// Funciona, muestra: Esto es fantástico
echo "Esto es {$genial}";
// Funciona
echo "Este cuadrado tiene {$cuadrado->width}00 centímetros de lado.";
// Funciona, las claves entre comillas sólo funcionan usando la sintaxis de llaves
echo "Esto funciona: {$arr['clave']}";
// Funciona
echo "Esto funciona: {$arr[4][3]}";
// Esto no funciona por la misma razón que $foo[bar] es incorrecto fuera de un string.
// En otras palabras, aún funcionaría, pero solamente porque PHP primero busca una
// constante llamada foo; se emitirá un error de nivel E_NOTICE
// (constante no definida).
echo "Esto está mal: {$arr[foo][3]}";
// Funciona. Cuando se usan arrays multidimensionales, emplee siempre llaves que delimiten
// a los arrays cuando se encuentre dentro de un string
echo "Esto funciona: {$arr['foo'][3]}";
// Funciona.
echo "Esto funciona: " . $arr['foo'][3];
echo "Esto también funciona: {$obj->valores[3]->nombre}";
echo "Este es el valor de la variable llamada $nombre: {${$nombre}}";
echo "Este es el valor de la variable llamada por el valor devuelto por getNombre(): {${getNombre()}}";
echo "Este es el valor de la variable llamada por el valor devuelto por \$objeto->getNombre(): {${$objeto->getNombre()}}";
//No funciona, muestra: Esto es el valor devuelto por getNombre(): {getNombre()}
echo "Esto es el valor devuelto por getNombre(): {getNombre()}";
?>
Complex syntax (braces)
This syntax is not called complex because it is complex, but because it allows the use of complex expressions.
Any scalar variable , array element , or object property with a string type representation can be included through this syntax. Simply write the expression in the same way it would appear outside the string, and delimit it with { y }
. Since {
can not be escaped, this syntax will be recognized only when the $
immediately follows the {
. Use {\$
to get {$ literal
.
Some examples:
$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
63608ms (34.7% slower)
$outstr = "literal$n$data$int$data$float$n";
47218ms (fastest)
$outstr =<<<EOS
literal$n$data$int$data$float$n
EOS;
47992ms (1.64% slower)
These rules I found in the manual PHP as notes contributed by other users, that I think you can answer your question:
Always use double quote strings ( ""
) for concatenation.
Put your variables in "Esto es una notación {$variable}"
, because it is the fastest method that still allows complex expansions like "This {$var['foo']} es {$obj->awesome()}!"
. You can not do that with the "${var}"
style.
Feel free to use single-quote strings ''
for FULLY literal strings such as keys / array values , < em> variable values , etc., since they are a TINY bit faster when you want strings that are not analyzed. But I had to do a billion iterations to find a measurable difference of 1.55%. So the only real reason why I would consider using single-quote strings for my literals is for the code cleanup , to make it very clear that the string is literal.
100 million iterations:
<?php
echo 'Esto es una cadena sencilla';
echo 'También se pueden incluir nuevas líneas en
un string de esta forma, ya que es
correcto hacerlo así';
// Resultado: Arnold una vez dijo: "I'll be back"
echo 'Arnold una vez dijo: "I\'ll be back"';
// Resultado: Ha borrado C:\*.*?
echo 'Ha borrado C:\*.*?';
// Resultado: Ha borrado C:\*.*?
echo 'Ha borrado C:\*.*?';
// Resultado: Esto no se expandirá: \n una nueva línea
echo 'Esto no se expandirá: \n una nueva línea';
// Resultado: Las variables $tampoco se $expandirán
echo 'Las variables $tampoco se $expandirán';
?>
See more iteration results .
Source Strings of characters (Strings) .