Requerir una vez a variable
Quiero llamar a require_once("test.php") pero no mostrar el resultado y guardarlo en variable como esta:
$test = require_once('test.php');
//some operations like $test = preg_replace(…);
echo $test;
Solución:
Prueba.php
<?php
$var = '/img/hello.jpg';
$res = <<<test
<style type="text/css">
body{background:url($var)#fff !important;}
</style>
test;
return $res;
?>
Main.php
<?php
$test = require_once('test.php');
echo $test;
?>
3 answers
Es posible?
Sí, pero necesita hacer un return
explícito en el archivo requerido:
//test.php
<? $result = "Hello, world!";
return $result;
?>
//index.php
$test = require_once('test.php'); // Will contain "Hello, world!"
Esto rara vez es útil - verifique la respuesta basada en búfer de salida de Konrad, o la de adam file_get_contents
- probablemente se adapten mejor a lo que desea.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-05 20:42:43
" El resultado " presumiblemente es una salida de cadena?
En ese caso se puede utilizar ob_start
para buffer dicha salida:
ob_start();
require_once('test.php');
$test = ob_get_contents();
EDITAR Desde la pregunta editada parece que quieres tener una función dentro del archivo incluido. En cualquier caso, esto probablemente sería el (mucho!) solución más limpia:
<?php // test.php:
function some_function() {
// Do something.
return 'some result';
}
?>
<?php // Main file:
require_once('test.php');
$result = test_function(); // Calls the function defined in test.php.
…
?>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-13 21:16:34
File_get_contents obtendrá el contenido del archivo. Si está en el mismo servidor y se hace referencia por ruta (en lugar de url), esto obtendrá el contenido de prueba.php. Si es remoto o referenciado por url, obtendrá la salida del script.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-13 21:17:05