如何将require_once输出传递给变量? [英] How to pass the require_once output to a variable?

查看:421
本文介绍了如何将require_once输出传递给变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用require_once("test.php")但不显示结果并将其保存到这样的变量中:

I want to call require_once("test.php") but not display result and save it into variable like this:

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

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

echo $test;

解决方案:

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;
?>

推荐答案

有可能吗?

Is it possible?

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

Yes, but you need to do an explicit return in the required file:

//test.php

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

//index.php

$test = require_once('test.php');  // Will contain "Hello, world!"

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

This is rarely useful - check Konrad's output buffer based answer, or adam's file_get_contents one - they are probably better suited to what you want.

这篇关于如何将require_once输出传递给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆