Sintaxis PHP Heredoc

Sheeraz Gul 15 febrero 2024
Sintaxis PHP Heredoc

La sintaxis heredoc se usa para declarar cadenas en PHP. Este tutorial describe y demuestra el uso de la sintaxis heredoc en PHP.

Sintaxis Heredoc en PHP

En PHP, la mayoría de los programadores utilizan dos métodos para declarar cadenas, uno con comillas simples ' ' y el otro con comillas dobles "", como se muestra a continuación.

$DemoString = 'Demo String';

$DemoString = "Demo String";

La sintaxis heredoc es otra forma de declarar cadenas en PHP. La sintaxis de heredoc toma al menos tres líneas de código y usa el operador <<< al principio para declarar la variable de cadena.

La sintaxis de este método es:

$DemoString = <<< identifier
// string
// string
// string
identifier;

El identificador se utiliza al principio y al final de la sintaxis. Puede usar cualquier palabra en lugar de un identificador aquí.

Aquí hay algunos puntos importantes cuando se trabaja con la sintaxis de heredoc.

  1. La variable heredoc debe tener al menos tres líneas que comiencen con <<< y un identificador y terminen con el mismo identificador.
  2. Las etiquetas HTML también se pueden usar en la sintaxis heredoc, que se implementará como elementos HTML.
  3. Nunca intente agregar funciones y condiciones en la sintaxis de heredoc. Esto generará errores.
  4. Para mostrar otras variables en la sintaxis de heredoc, puede usar llaves {}.

Probemos un ejemplo.

<?php
$DemoString = <<<Delftstack
Hello This is the Employee List from Delftstack.com<br>
1. Jack<br>
2. Michelle<br>
3. Jhonny<br>
4. Dana <br>
5. Natasha.
Delftstack;
echo $DemoString;
?>

El código anterior usa la sintaxis heredoc con el identificador Delftstack. Ver salida:

Hello This is the Employee List from Delftstack.com
1. Jack
2. Michelle
3. Jhonny
4. Dana
5. Natasha.

Aquí hay otro ejemplo con etiquetas HTML y otras variables.

<?php
$SiteName = "Delftstack";
$Message = "This is the best tutorials site for programmers";
$Print = <<<heredocDelftstack
<div >
    <div >
        <h1>{$SiteName}</h1>
        <p>{$Message}</p>
    </div>
</div>
heredocDelftstack;
echo $Print;
?>

El código anterior mostrará los datos en formato HTML. Ver salida:

Heredoc HTML

Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook