PHP包含/需要一个函数

时间:2011-06-19 11:09:23

标签: php return break

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

我希望这样做,因为我在单独的文件中有很多功能,并且它们顶部都有大量的共享代码。

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

file.php:

...
return "Something";

当返回的内容似乎突破了include_once而不是同步函数时,包含文件的返回是否可能会中断?

对于这个稍微有点过时的问题感到抱歉,希望我能说得对。

谢谢,

5 个答案:

答案 0 :(得分:6)

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

<强> include.php

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

<强> file.php

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

但你无法调用return $something;并将其作为调用脚本中的return语句。 return仅适用于当前范围。

修改

  

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

在这种情况下,为什么不将这个“共享代码”放入单独的函数中 - 这将很好地完成工作,因为具有函数的目的之一是重用代码在不同的地方而不再写

答案 1 :(得分:2)

return将不起作用,但是如果您尝试回显include文件中的某些内容并将其返回到其他位置,则可以使用输出缓冲区;

function sync() {
  ob_start();
  include "file.php";
  $output = ob_get_clean();
// now what ever you echoed in the file.php is inside the output variable
  return $output;
}

答案 2 :(得分:2)

我不认为它是那样的。包含不仅仅是将代码放在适当的位置,它还会对其进行评估。因此,返回意味着您的'include'函数调用将返回值。

另见手册中有关此内容的部分:

  

处理退货:有可能   在一个内部执行一个return()语句   包含文件以便终止   处理该文件并返回   调用它的脚本。

return语句返回包含的文件,并且不插入“return”语句。

manual有一个示例(示例#5),显示'return'的作用:

简化示例:

return.php

<?php  
$var = 'PHP';
return $var;
?>

testreturns.php

<?php   
$foo = include 'return.php';
echo $foo; // prints 'PHP'
?>

答案 3 :(得分:0)

我认为你期望return表现得更像异常而不是return语句。以下面的代码为例:

<强> return.php:     

return true;

?>

<强> exception.php:

<?php

throw new exception();

?>

执行以下代码时:

<?php

function testReturn() {
    echo 'Executing testReturn()...';
    include_once('return.php');
    echo 'testReturn() executed normally.';
}

function testException() {
    echo 'Executing testException()...';
    include_once('exception.php');
    echo 'testException() executed normally.';
}

testReturn();

echo "\n\n";

try {
    testException();
}
catch (exception $e) {}

?>

...结果得到以下输出:

  

执行testReturn()... testReturn()正常执行。

     

执行testException()...

如果您确实使用了例外方法,请确保将您的函数调用放在try...catch块中 - 在整个地方飞来飞行的异常对业务不利。

答案 4 :(得分:0)

像这样摇滚乐:

<强>的index.php

function foo() {
   return (include 'bar.php');
}
print_r(foo());

<强> bar.php

echo "I will call the police";
return array('WAWAWA', 'BABABA');

<强>输出

I will call the police
Array
(
    [0] => WAWAWA
    [1] => BABABA
)

只是告诉我如何

像这样:

return (include 'bar.php');

祝你有个美好的一天!