简体   繁体   English

如何在变量中包含来自不同文件的返回值

[英]How to include return values from a different file in a variable

I can return a value from embedded php within the variable (as below), but in this case I would like to get the output of a php file eg result.php. 我可以在变量中返回嵌入式php中的值(如下所示),但在这种情况下,我想得到一个php文件的输出,例如result.php。

var jsVar = "<?php echo 'thisisfromphp' ?>";

So running 'result.php' would produce a result to be returned. 所以运行'result.php'会产生一个返回的结果。 How could I grab this result from result.php and use it as the variable - I was thinking something like: 我怎么能从result.php中获取这个结果并将其用作变量 - 我想的是:

var jsVar = "<?php echo result.php ?>";

PS I would embed the php code from result.php in the variable (as above) but it all gets to messy.. PS我会将result.php中的php代码嵌入变量中(如上所述),但这一切都变得混乱了..

What you should do is refactor your code. 你应该做的是重构你的代码。 Don't have result.php echo something out that you try and capture. 没有result.php回显你尝试捕获的东西。 That's not resuable code. 这不是可恢复的代码。 Abstract whatever it does into a function that can be reused, then you can just require "result.php" and later callYourFunction() to get the desired output. 摘要无论它对可以重用的函数做什么,你都可以只require "result.php" ,然后callYourFunction()来获得所需的输出。

If, however, you are insistent on doing it this way (which, again, I advise against), you could: 但是,如果你坚持这样做(我建议反对),你可以:

ob_start();
require_once 'result.php';
$contents = ob_get_contents();
ob_end_clean();

// later...
var jsVar = <?php echo json_encode($contents); ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM