繁体   English   中英

PHP包含/需要一个函数

[英]PHP include/require within a function

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

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

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

file.php:

...
return "Something";

目前返回的东西似乎突破了include_once而不是sync函数,包含文件的返回是否有可能突然爆发?

对不起有点奇怪的问题,希望我让它变得有意义。

谢谢,

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

include.php

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

file.php

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

但你不能叫return $something; 并将其作为调用脚本中的return语句。 return仅在当前范围内有效。

编辑:

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

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

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;
}

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

另请参阅手册中有关此内容的部分:

处理返回:可以在包含的文件中执行return()语句,以终止该文件中的处理并返回调用它的脚本。

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

手册有一个示例(示例#5),显示“返回”的作用:

简化示例:

return.php

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

testreturns.php

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

Rock'n'roll喜欢这样:

的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');

祝你有美好的一天 !

我认为你期望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块中 - 在整个地方飞行异常对业务不利。

暂无
暂无

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

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