[英]How to check if an include() returned anything?
有没有办法检查通过include('to_include.php')
包含的文档是否返回了任何内容?
它是这样的:
//to_include.php
echo function_that_generates_some_html_sometimes_but_not_all_the_times();
//main_document.php
include('to_include.php');
if($the_return_of_the_include != '') {
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
}
因此,在将to_include.php
包含在主文档中之后,我想检查所包含的文档是否生成了任何内容。
我知道显而易见的解决方案是仅在main_document.php
使用function_that_generates_some_html_sometimes_but_not_all_the_times()
,但是在当前设置中这是不可能的。
如果您在谈论生成的输出,则可以使用:
ob_start();
include "MY_FILEEEZZZ.php";
function_that_generates_html_in_include();
$string = ob_get_contents();
ob_clean();
if(!empty($string)) { // Or any other check
echo $some_crap_that_makes_my_life_difficult;
}
可能必须调整ob_调用...我认为这是正确的,但内存就是金鱼。
您也可以设置变量的内容,例如$GLOBALS['done'] = true;
在包含文件中生成内容时,请在主文件中进行检查。
使function_that_generates_some_html_sometimes_but_not_all_the_times()
在输出内容并设置变量时返回内容:
//to_include.php
$ok=function_that_generates_some_html_sometimes_but_not_all_the_times();
//main_document.php
$ok='';
include('to_include.php');
if($ok != '') {
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
}
给定问题的措辞,听起来好像您想要这样:
//to_include.php
return function_that_generates_some_html_sometimes_but_not_all_the_times();
//main_document.php
$the_return_of_the_include = include 'to_include.php';
if (empty($the_return_of_the_include)) {
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
} else {
echo $the_return_of_the_include;
}
哪种应该适合您的情况。 这样,您就不必担心输出缓冲,变量蠕变等问题 。
我不确定是否遗漏了问题的重点,但是....
function_exists();
如果定义了函数,则将返回true。
include()
如果包含文件,则返回true。
所以将其中一个或两个都包裹在if()中,除非我错了,否则你就很好了
if(include('file.php') && function_exists(my_function))
{
// wee
}
尝试
// to_include.php
$returnvalue = function_that_generates_some_html_sometimes_but_not_all_the_times();
echo $returnvalue;
//main_document.php
include('to_include.php');
if ( $returnvalue != '' ){
echo $do_a_little_dance_make_a_little_love_get_down_tonight;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.