Re: [PHP-DEV] Php 5.3 Snap - Lambda functions and $this scope

2008-07-24 Thread Christian Seiler

Hi,


Wouldn't it be better (and maybe safer) to allow the use of $this as a
closure instead of passing it to the new lambda function?


We had that in a previous patch. We had quite a few discussions on what
the best syntax would be, actually.

In the end, Dmitry and I chose to implement it in this way because it
seemed more consistent with current PHP behaviour and because more
people on internals seemed to like it than dislike it.

As for the consistency with current PHP behaviour: $this is always
present in any class method which is non-static. Every other variable
(except superglobals) used in a method or function must explicitly be
defined - either as a parameter, or in the function or via 'global
$foo'. So $this is already special. So using the presence or absence of
the 'static' keyword in front of the 'function' keyword to determine
whether $this is available inside the closure seems much more natural.

Of course, there will be people who disagree with this. But we've
already discussed closure syntax quite a bit while discussion my
original patch and I believe the compromise we've reached is quite
acceptable for everybody.

Regards,
Christian

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



[PHP-DEV] Php 5.3 Snap - Lambda functions and $this scope

2008-07-23 Thread George Antoniadis
This is based on a bug submitted at http://bugs.php.net/bug.php?id=45604

Description:

When creating a normal function inside a class and calling it, the
function doesn't have access to $this.
"Fatal error: Using $this when not in object context"

When creating a lambda function inside a class, $this is visible from
the new function's scope and can be accessed normally.

Wouldn't it be better (and maybe safer) to allow the use of $this as a
closure instead of passing it to the new lambda function?
Currently trying to use $this as a closure dies with a "Fatal error:
Cannot use $this as lexical variable" error.

Example for the suggestion.
$x = function () use ($this) { return $this->hello; };

Reproduce code:
---

> 
> class something
> {
>  public $hello = 'Hello world!';
>
>  public function world()
>  {
>   $x = function () { return $this->hello; };
>   return $x();
>  }
> }
>
> $s = new something();
> echo $s->world();
>
> ?>



Expected result:

Not to be able to use $this.