本文实例讲述了php闭包中使用use声明变量的作用域。分享给大家供大家参考,具体如下:
<?php function getClosure($i) { $i = $i.'-'.date('H:i:s'); return function ($param) use ($i) { echo "--- param: $param ---\n"; echo "--- i: $i ---\n"; }; } $c = getClosure(123); $i = 456; $c('test'); sleep(3); $c2 = getClosure(123); $c2('test'); $c('test'); /* output: --- param: test --- --- i: 123-21:36:52 --- --- param: test --- --- i: 123-21:36:55 --- --- param: test --- --- i: 123-21:36:52 --- */
如上,闭包中使用use
声明的变量来自于生成闭包实例时所在作用域内的同名变量,而不是来自于运行闭包时所在作用域内的同名变量。
而闭包的函数参数则是和正常的函数参数一样来自于运行时所在作用域内的同名变量。
以下为opcode:
Finding entry points
Branch analysis from position: 0
Jump found. Position 1 = -2
filename: /tmp/testclosure.php
function name: (null)
number of ops: 20
compiled vars: !0 = $c, !1 = $i, !2 = $c2
line #* E I O op fetch ext return operands
-------------------------------------------------------------------------------------
2 0 E > NOP
11 1 SEND_VAL 123
2 DO_FCALL 1 $0 'getclosure'
3 ASSIGN !0, $0
12 4 ASSIGN !1, 456
13 5 INIT_FCALL_BY_NAME !0
6 SEND_VAL 'test'
7 DO_FCALL_BY_NAME 1
14 8 SEND_VAL 3
9 DO_FCALL 1 'sleep'
15 10 SEND_VAL 123
11 DO_FCALL 1 $5 'getclosure'
12 ASSIGN !2, $5
16 13 INIT_FCALL_BY_NAME !2
14 SEND_VAL 'test'
15 DO_FCALL_BY_NAME 1
17 16 INIT_FCALL_BY_NAME !0
17 SEND_VAL 'test'
18 DO_FCALL_BY_NAME 1
29 19 > RETURN 1
Function