[prev in list] [next in list] [prev in thread] [next in thread] 

List:       php-internals
Subject:    Re: [PHP-DEV] On closures and lamdba
From:       Joey Smith <joey () joeysmith ! com>
Date:       2010-02-21 2:55:10
Message-ID: 20100221025510.GA9984 () joeysmith ! com
[Download RAW message or body]

> Oh, yes, the question:
>
> Wouldn't you agree that it is better for PHP to use the word closure as  
> it is being used in the JavaScript community?

There's a pretty big difference between how PHP implements closures and how
JavaScript implements them - in PHP, you have to explicitly request which
variables will be bound to the closure. Here's an example I've been using
on Freenode's ##PHP to demonstrate how a PHP closure might work.
=================
$array = array(
	array('foo' => 17, 'bar'=>'last'),
	array('foo' => 1,  'bar'=>'first'),
	array('foo' => 3,  'bar'=>'middle'),
);
function buildSorter($key) { 
	return function ($a, $b) use ($key) {
		if ($a[$key] == $b[$key]) return 0; return ($a[$key] < $b[$key]) ? -1:1; 
	};
}
$sort = buildSorter('foo');
usort($array, $sort);
var_dump($array);
=================

Not an example that's going to rock anyone's world, obviously, but I think
it's illustrative.

However, because of an implementation detail (all anonymous functions are
now implemented as instance of class 'Closure'), it might be hard to enforce a
strict use of the word 'closure' here - although, it *is* kind of interesting
to look at a var_dump() of $sort:

object(Closure)#1 (2) {
  ["static"]=>
  array(1) {
    ["key"]=>
    string(3) "foo"
  }
  ["parameter"]=>
  array(2) {
    ["$a"]=>
    string(10) "<required>"
    ["$b"]=>
    string(10) "<required>"
  }
}

Unfortunately, we're not allowed to query for that 'static' property
(Catchable fatal error: Closure object cannot have properties) and are
are explicitly discouraged from relying on this detail of implementation
("Anonymous functions are currently implemented using the  Closure class.
This is an implementation detail and should not be relied upon.")

So to answer your question, for my money, since I can't currently tell the
difference in a programmatic way between an 'anonymous function' and a full
'closure', I don't find it that worrisome that the PHP world somewhat
conflates the two terms.

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic