I have several php files to include and they must act as a function in a protected scope. A closure is intended to load them (include) and execute. Though I encounter a strange effect on coding these closures. All php files ends with a return statement.
function myClosure () {
include 'file.php';
return $closure; // initialized in file.php
};
$func = myClosure();
echo $func('1'); // echoes '2'
echo $func('4'); // echoes '8'
where file.php is something like
<?php
$closure = function($a) {
$b = $a + $a;
return $b;
};
?>
This works. However, I would like to have the surrounding closure 'function($b)' (without the 'return') in the main code, not in the external file. Sadly, the following doesn't work as expected:
function myClosure () {
$closure = function($a) {
include 'file.php';
};
return $closure;
};
$func = myClosure();
echo $func('1'); // echoes null
echo $func('4'); // echoes null
where file.php is something like
<php
$b = $a + $a;
return $b;
?>
Changing the includes into include_once gives the same for the first example, and not for the second example: second echo fails to run. I'm suspecting now that this behaviour is either a bug (php 5) or due to doing some illegal trick with include. Maybe the 'return's in the code are bound to their context? I would appreciate some help, be it a lesson on clean coding, be it a correct trick.