Passing Variables to an Include in PHP

If you have ever needed to pass variables in an include to make it dynamic, we leave you a function that will save you the work.
// Include con Variables function includeWithVariables($filePath, $variables = array(), $print = true) { $output = NULL; if(file_exists($filePath)){ // Extrae las variables en un entorno local extract($variables); // Empieza el buffering de salida ob_start(); // Include el archivo include $filePath; // Termina el buffering y devuelve su contenido $output = ob_get_clean(); } if ($print) { print $output; } return $output; }
After placing our function, we can use it wherever we want by passing it the variables.
<?php includeWithVariables('detalles.php', array('detalle' => 'Hola')); ?>
And inside “detalles.php” we could call any variable simply with
<? echo $detalle; ?>
As you have seen, the solution to pass variables or parameters to an include is very simple. We hope to continue helping and if you have any questions, do not hesitate to leave your comment.