PHP在函数中包含/需要 [英] PHP include/require within a function

查看:51
本文介绍了PHP在函数中包含/需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在PHP函数内部的包含文件中包含return语句?

Is it possible to have return statements inside an included file that is inside a function in PHP?

我希望这样做是因为我在其中有很多函数单独的文件,它们的顶部都有很大一部分共享代码。

I am looking to do this as I have lots of functions in separate files and they all have a large chunk of shared code at the top.

As in
function sync() {
  include_once file.php;
  echo "Test";
}

file.php:

...
return "Something";

此刻,返回值似乎从include_once而不是sync函数中消失了,是吗

At the moment the return something appears to break out of the include_once and not the sync function, is it possible for the included file's return to break out?

对这个有点奇怪的问题很抱歉,希望我说得对。

Sorry for the slightly odly worked question, hope I made it make sense.

谢谢

推荐答案

您可以通过 return将数据从包含的文件返回到调用文件中语句。

include.php

return array("code" => "007", "name => "James Bond");

file.php

$result = include_once "include.php";
var_dump("result);

但是您不能打电话给返回$东西; 并将其作为调用脚本中的return语句。 返回仅在当前范围内起作用。

But you cannot call return $something; and have it as return statement within calling script. return works only within current scope.

编辑:


我正在这样做,因为我在单独的文件中有很多
个函数,而
它们都有很大一部分共享的
代码位于顶部。

I am looking to do this as I have lots of functions in separate files and they all have a large chunk of shared code at the top.

在这种情况下,为什么不将共享代码放入单独的函数中, 这将很好地完成工作,因为拥有功能的目的之一是在不同的地方重用代码而无需再次编写

In this case why don't you put this "shared code" into separate functions instead -- that will do the job nicely as one of the purposes of having functions is to reuse your code in different places without writing it again.

这篇关于PHP在函数中包含/需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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