为什么后期静态绑定在匿名函数中不起作用?
Why late static binding doesn't work inside anonymous function?
我有 PHP 如下代码
<?php
class Test {
public static function bar(array $ids) {
return array_map(function($id) {
return static::foo($id);
}, $ids);
}
public static function foo($id) {
return "halo {$id}";
}
}
class Test1 extends Test {
public static function foo($id) {
return "hi {$id}";
}
}
$className = Test1::class;
//Let's say line above is input from user or some other code.
$ids = [1, 2, 3, 4, 5];
print_r(call_user_func([$className, 'bar'], $ids));
我预计上面的代码会 return
Array
(
[0] => hi 1
[1] => hi 2
[2] => hi 3
[3] => hi 4
[4] => hi 5
)
但奇怪的是,它 returns
Array
(
[0] => halo 1
[1] => halo 2
[2] => halo 3
[3] => halo 4
[4] => halo 5
)
这是为什么?
我的PHP版本低于
PHP 5.5.9-1ubuntu4.9 (cli) (built: Apr 17 2015 11:44:57)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
但奇怪的是,HHVM return正是我所期望的。
HipHop VM 3.6.5 (rel)
Compiler: tags/HHVM-3.6.5-0-g20a30678cd67fad96602ffd93e69780d001ce57f
Repo schema: 53a4026d3732c3584cffef19fa47fea655be3c4f
这是 5.5.14 之前的错误。有关详细信息,请参阅 the changelog。可能是这样的:
Fixed bug #66622 (Closures do not correctly capture the late bound class (static::) in some cases).
编辑:link 以确认不同版本中的错误:https://3v4l.org/BiYk2
我有 PHP 如下代码
<?php
class Test {
public static function bar(array $ids) {
return array_map(function($id) {
return static::foo($id);
}, $ids);
}
public static function foo($id) {
return "halo {$id}";
}
}
class Test1 extends Test {
public static function foo($id) {
return "hi {$id}";
}
}
$className = Test1::class;
//Let's say line above is input from user or some other code.
$ids = [1, 2, 3, 4, 5];
print_r(call_user_func([$className, 'bar'], $ids));
我预计上面的代码会 return
Array
(
[0] => hi 1
[1] => hi 2
[2] => hi 3
[3] => hi 4
[4] => hi 5
)
但奇怪的是,它 returns
Array
(
[0] => halo 1
[1] => halo 2
[2] => halo 3
[3] => halo 4
[4] => halo 5
)
这是为什么?
我的PHP版本低于
PHP 5.5.9-1ubuntu4.9 (cli) (built: Apr 17 2015 11:44:57)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
但奇怪的是,HHVM return正是我所期望的。
HipHop VM 3.6.5 (rel)
Compiler: tags/HHVM-3.6.5-0-g20a30678cd67fad96602ffd93e69780d001ce57f
Repo schema: 53a4026d3732c3584cffef19fa47fea655be3c4f
这是 5.5.14 之前的错误。有关详细信息,请参阅 the changelog。可能是这样的:
Fixed bug #66622 (Closures do not correctly capture the late bound class (static::) in some cases).
编辑:link 以确认不同版本中的错误:https://3v4l.org/BiYk2