【发布时间】:2017-04-12 03:40:56
【问题描述】:
我有几个 php 文件要包含,它们必须作为受保护范围内的函数。闭包旨在加载它们(包括)并执行。尽管我在编写这些闭包时遇到了奇怪的效果。所有 php 文件都以 return 语句结尾。
function myClosure () {
include 'file.php';
return $closure; // initialized in file.php
};
$func = myClosure();
echo $func('1'); // echoes '2'
echo $func('4'); // echoes '8'
file.php 类似于
<?php
$closure = function($a) {
$b = $a + $a;
return $b;
};
?>
这行得通。但是,我想在主代码中而不是在外部文件中包含周围的闭包'function($b)'(没有'return')。遗憾的是,以下内容无法按预期工作:
function myClosure () {
$closure = function($a) {
include 'file.php';
};
return $closure;
};
$func = myClosure();
echo $func('1'); // echoes null
echo $func('4'); // echoes null
file.php 类似于
<php
$b = $a + $a;
return $b;
?>
将包含更改为 include_once 会为第一个示例提供相同的结果,而不是第二个示例:第二个 echo 无法运行。 我现在怀疑这种行为要么是一个错误(php 5),要么是由于对 include 做了一些非法的把戏。也许代码中的“返回”绑定到他们的上下文? 我会很感激一些帮助,无论是关于清洁编码的课程,还是正确的技巧。
【问题讨论】:
-
你没有在关闭中返回。正如您所说,
include 'file.php'将转换为... return $b,但是,$closure = function ...也是作用域的,因此return $closure实际上将返回 null,因为它是 PHP 提供的默认值。长话短说,只需在myClosure中执行return include 'file.php'。
标签: php include return closures