Page 1 of 1

Closures in PHP - sort of

Posted: Sun May 28, 2006 10:21 am
by Chris Corbyn
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:

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
I decided to see a way through it in PHP, and create_function() is made for this sort of thing right?

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

?>
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 :)

Posted: Sun May 28, 2006 10:38 am
by Chris Corbyn
Oh my god please ignore me.... this only works the first time. It can't write back to the closure of course. Duh! Time for another coffee.

Posted: Sun May 28, 2006 12:00 pm
by Weirdan
d11 wrote: I've only just stumbled across closures in C/C
Ehh... excuse my ignorance, how closures are possible in C/C ?

Posted: Sun May 28, 2006 12:11 pm
by Chris Corbyn
Weirdan wrote:
d11 wrote: I've only just stumbled across closures in C/C
Ehh... excuse my ignorance, how closures are possible in C/C ?
I was watching a demo in C the other day using function pointers. I'll see if I can dig it up :)

Posted: Sun May 28, 2006 12:25 pm
by Flamie
Good examples of closures in various languages: (copy paste into browser)
http://en.wikipedia.org/wiki/Closure_(c ... )#Examples

from that same page they say:
Scheme was the first programming language to have fully general, lexically scoped closures. Virtually all functional programming languages, as well as the Smalltalk-descended object-oriented programming languages, support some form of closures.
You're right tho, I'm having a hard time seeing how it can be done in PHP.

Posted: Sun May 28, 2006 12:43 pm
by Chris Corbyn
Ok... C and C++ don't have *real* closures. They emulate them by using pointers to function objects or functors as they call them.

I'm scouring for code that show it but everyone's gone way overboard with the examples, we only need to see something basic happen like a number increment each time the closure gets used.
You're right tho, I'm having a hard time seeing how it can be done in PHP.
Well I've had a little look around and there are some emulations again but it's nasty... let's face it, PHP started off as a simple set of perl scripts to do some basic web stuff.... who ever imagined it would grow to this scale?