php闭包 js闭包,JavaScript闭包与PHP闭包的区别是什么?

NikiCaziz punjani提出了一个问题:Javascript closures vs PHP closures, what's the difference?,或许与您遇到的问题类似。

One difference is how both cope with storing the context in which an anonymous function is executed:

// JavaScript:

var a = 1;

var f = function() {

console.log(a);

};

a = 2;

f();

// will echo 2;

// PHP

$a = 1;

$f = function() {

echo $a;

};

$a = 2;

$f();

// will result in a "PHP Notice: Undefined variable: a in Untitled.php on line 5"

To fix this notice you'll have to use the use syntax:

$a = 1;

$f = function() use ($a) {

echo $a;

};

$a = 2;

$f();

// but this will echo 1 instead of 2 (like JavaScript)

To have the anonymous function behave somehow like the JavaScript counterpart you'll have to use references:

$a = 1;

$f = function() use (&$a) {

echo $a;

};

$a = 2;

$f();

// will echo 2

I think this is the most striking difference between JavaScript and PHP closures.

Second difference is that every JavaScript closure has a this context available which means, that you can use this inside the closure itself (although it's often quite complicated to figure out what this actually refers to) - PHP's current stable version (PHP 5.3) does not yet support $this inside a closure, but PHP's upcoming version (PHP 5.4) will support $this binding and rebinding using $closure->bind($this) (See the Object Extension RFC for more info.)

Third difference is how both languages treat closures assigned to object properties:

// JavaScript

var a = {

b: function() {}

};

a.b(); // works

// PHP

$a = new stdClass();

$a->b = function() {};

$a->b(); // does not work "PHP Fatal error: Call to undefined method stdClass::b() in Untitled.php on line 4"

$f = $a->b;

$f(); // works though

The same is true if closures are assigned to properties in class definitions:

class A {

public $b;

public function __construct() {

$this->b = function() {};

}

public function c() {

$this->b();

}

}

$a = new A();

// neither

$a->b();

// nor

$a->c();

// do work

Fourth difference: JavaScript Closures are full fledged objects, wheres in PHP they are restricted objects. For instance, PHP Closures cannot have properties of their own:

$fn = function() {};

$fn->foo = 1;

// -> Catchable fatal error: Closure object cannot have properties

while in JavaScript you can do:

var fn = function() {};

fn.foo = 1;

fn.foo; // 1

Fifth difference: Returned closures can be immediately called upon in Javascript:

var fn = function() { return function() { alert('Hi');}}

fn()();

Not in PHP:

$fn = function() { return function() { echo('Hi');};};

$fn()(); // syntax error

希望本文对你有帮助,欢迎支持JavaScript中文网

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值