首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHP5.4- 'closure $this支持‘

PHP5.4- 'closure $this支持‘
EN

Stack Overflow用户
提问于 2011-04-21 01:06:50
回答 2查看 32.6K关注 0票数 68

我看到PHP5.4计划中的新特性是:特征、数组取消引用、JsonSerializable接口和一些被称为“closure $this support”的东西。

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

虽然其他的不是一目了然(JsonSerialiable,数组取消引用),就是我查了细节(特征),我不确定什么是“闭包$this支持”。我在谷歌上搜索它或在php.net上找到任何关于它的东西都没有成功

有人知道这应该是什么吗?

如果非要我猜的话,应该是这样的:

代码语言:javascript
复制
$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;
                     }
                 };

重要的是(即使这个例子是微不足道的),在过去,一旦构造了闭包,绑定的'use‘变量就是固定的。有了“closure $this支持”,他们更像是你可以摆弄的成员。

这听起来是否正确和/或接近和/或合理?有人知道“closure $this支持”是什么意思吗?

EN

回答 2

Stack Overflow用户

发布于 2012-02-25 03:14:02

基于@Gordon的回答,可以模仿闭包的一些老生常谈的方面-- PHP 5.3中的$this。

代码语言:javascript
复制
<?php
class A
{
    public $value = 12;
    public function getClosure()
    {
        $self = $this;
        return function() use($self)
        {
            return $self->value;
        };
    }
}

$a = new A;
$fn = $a->getClosure();
echo $fn(); // 12
票数 22
EN

Stack Overflow用户

发布于 2016-06-17 04:50:43

在其他答案的基础上,我认为这个例子将演示什么是可能的PHP 5.4+:

代码语言:javascript
复制
<?php

class Mailer {
    public    $publicVar    = 'Goodbye ';
    protected $protectedVar = 'Josie ';
    private   $privateVar   = 'I love CORNFLAKES';

    public function mail($t, $closure) {
        var_dump($t, $closure());
    }
}

class SendsMail {
    public    $publicVar    = 'Hello ';
    protected $protectedVar = 'Martin ';
    private   $privateVar   = 'I love EGGS';

    public function aMailingMethod() {
        $mailer = new Mailer();
        $mailer->mail(
            $this->publicVar . $this->protectedVar . $this->privateVar,
            function() {
                 return $this->publicVar . $this->protectedVar . $this->privateVar;
            }
        );
    }
}

$sendsMail = new SendsMail();
$sendsMail->aMailingMethod();

// prints:
// string(24) "Hello Martin I love EGGS"
// string(24) "Hello Martin I love EGGS"

请参阅:https://eval.in/private/3183e0949dd2db

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5734011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档