Closures in PHP - sort of
Posted: Sun May 28, 2006 10:21 am
I'll be the first to admit that I've only just stumbled across closures in C/C++ and JavaScript but someone on Sitepoint mentioned that PHP can't do closures.
Based on this in JavaScript:
I decided to see a way through it in PHP, and create_function() is made for this sort of thing right?
So am I missing something significant here? By the way I don't need this for anything, I'm just experimenting with ideas as usual 
Based on this in JavaScript:
Code: Select all
function myClosure(arg1, arg2)
{
var localVar = 8;
function exampleReturned(innerArg)
{
return ((arg1 + arg2)/(innerArg + localVar));
}
return exampleReturned;
}
var globalVar = myClosure(2, 4);
alert(globalVar(4)); //0.5
Code: Select all
<?php
function myClosure($arg1, $arg2)
{
$localVar = 8;
$exampleReturned = create_function('$innerArg', '
return (('.$arg1.' + '.$arg2.')/($innerArg + '.$localVar.'));
');
return $exampleReturned;
}
$globalFunc = myClosure(2, 4);
echo $globalFunc(4); //0.5
?>