封闭内部包括

时间:2016-11-28 12:07:57

标签: php include return closures

我要包含几个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;
};
?>

这很有效。但是,我想在主代码中有周围的闭包'函数($ 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;
?>

将includes更改为include_once为第一个示例提供相同的内容,而不是第二个示例:第二个echo无法运行。 我现在怀疑这种行为要么是一个bug(php 5),要么是因为使用include做了一些非法技巧。也许代码中的'返回符合它们的上下文? 我会感谢一些帮助,无论是关于清洁编码的一课,还是一个正确的技巧。

1 个答案:

答案 0 :(得分:0)

由于闭包是作用域的(正如OP已经提到的那样),你必须在returnmyClosure

你现在有:

function myClosure () {
    $closure = function($a) {
       include 'file.php';
    };
    return $closure;
};

只需将其更改为:

function myClosure () {
    $closure = function($a) {
        return include 'file.php';
    };
    return $closure;
};

您应该收到以下内容:

int(2) int(4)

鉴于你保持

$func = myClosure();
var_dump($func('1')); 
var_dump($func('2'));
相关问题