Require_once变量

swa*_*er7 22 php file

我想调用require_once("test.php")但不显示结果并将其保存到变量中,如下所示:

$test = require_once('test.php');

//some operations like $test = preg_replace(…);

echo $test;
Run Code Online (Sandbox Code Playgroud)

解:

test.php的

<?php
$var = '/img/hello.jpg';

$res = <<<test

<style type="text/css">
body{background:url($var)#fff !important;}
</style>

test;

return $res;
?>
Run Code Online (Sandbox Code Playgroud)

main.php

<?php
$test = require_once('test.php');

echo $test;
?>
Run Code Online (Sandbox Code Playgroud)

Pek*_*ica 29

可能吗?

是的,但您需要return在所需文件中进行明确说明:

//test.php

<? $result = "Hello, world!"; 
  return $result;
?>

//index.php

$test = require_once('test.php');  // Will contain "Hello, world!"
Run Code Online (Sandbox Code Playgroud)

这很少有用 - 检查Konrad基于输出缓冲区的答案,或亚当的答案file_get_contents- 它们可能更适合您想要的.


Kon*_*lph 26

"结果"可能是字符串输出?

在这种情况下,您可以使用ob_start缓冲输出:

ob_start();
require_once('test.php');
$test = ob_get_contents();
Run Code Online (Sandbox Code Playgroud)

编辑从编辑的问题看起来很像你想在包含的文件中有一个功能.在任何情况下,这可能是(更多!)更清洁的解决方案:

<?php // test.php:

function some_function() {
    // Do something.
    return 'some result';
}

?>
Run Code Online (Sandbox Code Playgroud)
<?php // Main file:

require_once('test.php');

$result = test_function(); // Calls the function defined in test.php.
…
?>
Run Code Online (Sandbox Code Playgroud)

  • 只是为了完整性:如果你使用'ob_start()',在将输出分配给变量后不要忘记'ob_end_clean()'. (2认同)