PHP 5.4 - 'closure $ this support' [英] PHP 5.4 - 'closure $this support'

查看:103
本文介绍了PHP 5.4 - 'closure $ this support'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到PHP 5.4的新计划功能是:traits,数组取消引用,一个JsonSerializable接口和一些被称为'的闭包$ this support '

I see that the new planned features for PHP 5.4 are: traits, array dereferencing, a JsonSerializable interface and something referred to as 'closure $this support'

http://en.wikipedia.org/wiki/Php#Release_history

虽然其他人或者立即清除(JsonSerialiable,数组取消引用)或者我查看的细节(traits),我不知道什么'支持。我已经失败了,或者在php.net上找不到任何东西。

While the others are either immediately clear (JsonSerialiable, array dereferencing) or i looked up the specifics (traits), I am not sure what 'closure $this support' is. I have been unsuccessful googling for it or finding anything about it on php.net

有没有人知道这是什么?

Does anyone know what this is supposed to be?

如果我不得不猜测,它会是这样的:

If i had to guess, it would mean something like this:

$a = 10; $b = 'strrrring';
//'old' way, PHP 5.3.x
$myClosure = function($x) use($a,$b)
             {
                 if (strlen($x) <= $a) return $x;
                 else return $b;
             };

//'new' way with closure $this for PHP 5.4
$myNewClosure = function($x) use($a as $lengthCap,$b as $alternative)
                 {
                     if(strlen($x) <=  $this->lengthCap)) return $x;
                     else 
                     {
                         $this->lengthCap++;  //lengthcap is incremented for next time around
                         return $this->alternative;
                     }
                 };

重要性(即使这个例子很简单)是在过去一旦构造闭包bound'use'变量是固定的。有了'关闭$这支持',他们更像是你可以混乱的成员。

The significance (even if this example is trivial) being that in the past once the closure is constructed the bound 'use' variables are fixed. With 'closure $this support' they are more like members you can mess with.

这听起来是否正确和/或接近和/或合理?

Does this sound correct and/or close and/or reasonable? Does anyone know what this 'closure $this support' means?

推荐答案

这已经计划为PHP 5.3,但

This was already planned for PHP 5.3, but


对于PHP 5.3 $,对Closures的这种支持被删除了,因为没有达成共识,如何以一种正常的方式实现。这个RFC描述了可以在下一个PHP版本中实现它的可能的道路。

For PHP 5.3 $this support for Closures was removed because no consensus could be reached how to implement it in a sane fashion. This RFC describes the possible roads that can be taken to implement it in the next PHP version.

这的确意味着你可以引用对象实例(现场演示

It indeed means you can refer to the object instance (live demo)

<?php
class A {
  private $value = 1;
  public function getClosure() 
  {
    return function() { return $this->value; };
  }
}

$a = new A;
$fn = $a->getClosure();
echo $fn(); // 1

有关讨论,请参阅PHP Wiki

For a discussion, see the PHP Wiki

  • Closures: Object extension

和历史兴趣:

这篇关于PHP 5.4 - 'closure $ this support'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆