php 如何将 require_once 输出传递给变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2830366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass the require_once output to a variable?
提问by swamprunner7
I want to call require_once("test.php") but not display result and save it into variable like this:
我想调用 require_once("test.php") 但不显示结果并将其保存到变量中,如下所示:
$test = require_once('test.php');
//some operations like $test = preg_replace(…);
echo $test;
Solution:
解决方案:
test.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;
?>
回答by Pekka
Is it possible?
是否可以?
Yes, but you need to do an explicit returnin the required file:
是的,但您需要return在所需文件中进行显式操作:
//test.php
<? $result = "Hello, world!";
return $result;
?>
//index.php
$test = require_once('test.php'); // Will contain "Hello, world!"
This is rarely useful - check Konrad's output buffer based answer, or adam's file_get_contentsone - they are probably better suited to what you want.
这很少有用 - 检查 Konrad 的基于输出缓冲区的答案,或 adam 的答案file_get_contents- 它们可能更适合您想要的。
回答by Konrad Rudolph
“The result” presumably is a string output?
“结果”大概是一个字符串输出?
In that case you can use ob_startto buffer said output:
在这种情况下,您可以使用ob_start缓冲所述输出:
ob_start();
require_once('test.php');
$test = ob_get_contents();
EDITFrom the edited question it looks rather like you want to have a functioninside the included file. In any case, this would probably be the (much!) cleaner solution:
编辑从编辑的问题看来,您希望在包含的文件中包含一个函数。无论如何,这可能是(非常!)更清洁的解决方案:
<?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.
…
?>
回答by Adam Hopkinson
file_get_contentswill get the content of the file. If it's on the same server and referenced by path (rather than url), this will get the content of test.php. If it's remote or referenced by url, it will get the output of the script.
file_get_contents将获取文件的内容。如果它在同一台服务器上并通过路径(而不是 url)引用,这将获得 test.php 的内容。如果它是远程的或被 url 引用,它将获得脚本的输出。

