我看到PHP5.4计划中的新特性是:特征、数组取消引用、JsonSerializable接口和一些被称为“closure $this support
”的东西。
http://en.wikipedia.org/wiki/Php#Release_history
虽然其他的不是一目了然(JsonSerialiable,数组取消引用),就是我查了细节(特征),我不确定什么是“闭包$this支持”。我在谷歌上搜索它或在php.net上找到任何关于它的东西都没有成功
有人知道这应该是什么吗?
如果非要我猜的话,应该是这样的:
$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支持”是什么意思吗?
发布于 2012-02-25 03:14:02
基于@Gordon的回答,可以模仿闭包的一些老生常谈的方面-- PHP 5.3中的$this。
<?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
发布于 2016-06-17 04:50:43
在其他答案的基础上,我认为这个例子将演示什么是可能的PHP 5.4+:
<?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://stackoverflow.com/questions/5734011
复制相似问题