php 从包含文件返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1314162/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:00:02  来源:igfitidea点击:

Return from include file

php

提问by bear

in PHP, how would one return from an included script back to the script where it had been included from?

在 PHP 中,如何从包含的脚本返回到包含它的脚本?

IE:

IE:

1 - main script 2 - application 3 - included

1 - 主脚本 2 - 应用程序 3 - 包括

Basically, I want to get back from 3 to 2, return() doesn't work.

基本上,我想从 3 回到 2, return() 不起作用。

Code in 2 - application

代码 2 - 应用程序

$page = "User Manager";
if($permission["13"] !=='1'){
    include("/home/radonsys/public_html/global/error/permerror.php");
    return();
}

回答by Frank Farmer

includeme.php:

包含.php:

$x = 5;
return $x;

main.php:

主文件:

$myX = require 'includeme.php'; 

also gives the same result

也给出了相同的结果

This is one of those little-known features of PHP, but it can be kind of nice for setting up really simple config files.

这是 PHP 鲜为人知的特性之一,但它可以很好地设置非常简单的配置文件。

回答by instanceof me

returnshould work, as stated in the documentation.

return应该可以工作,如文档所述

If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call.

如果当前脚本文件被include()ed 或require()ed,则控制被传递回调用文件。此外,如果当前脚本文件被 include() 处理,则给 return() 的值将作为 include() 调用的值返回。

回答by Gravy

I know that this has already been answered, but I think I have a nice solution...

我知道这已经得到了回答,但我想我有一个很好的解决方案......

main.php

主文件

function test()
{
    $data = 'test';
    ob_start();
        include( dirname ( __FILE__ ) . '/included.php' );
    return ob_get_clean();
}

included.php

包含.php

<h1>Test Content</h1>
<p>This is the data: <?php echo $data; ?></p>

I just included $datato show that you can still pass data to the included file, as well as return the included file.

我只是$data为了表明您仍然可以将数据传递给包含的文件,以及返回包含的文件。

回答by Eevee

Hm, the PHP manualdisagrees with you. returnshould bail you out of an included file. It won't work from within a function, of course.

嗯,PHP 手册不同意你的看法。 return应该让你摆脱包含的文件。当然,它不会在函数内工作。

回答by Brian

See Example #5in the documentation for include.

请参阅文档中的示例 #5以获取include

You can get the return value of the script when including it, like:

您可以在包含脚本时获取脚本的返回值,例如:

$foo = include 'script.php';