create_function而不是lambda-function avartaco

时间:2013-09-10 15:48:39

标签: php

我试图实施avartaco,就像gravatar一样。

为了使它在php版本中工作< 5.3

  

如果你想让它在低于5.3.0的PHP上运行,找到字符串

     

array_walk($ shape,function(& $ coord,$ index,$ mult){$ coord * = $ mult;   },self :: SPRITE_SIZE);

     

并使用create_function()而不是lambda-function重写它。

我在同一行array_walk中收到错误Parse error: syntax error, unexpected T_FUNCTION。我的php版本是5.2.17< 5.3 但我不知道createfunction重写是什么意思?

那么我应该在该行中进行哪些更改以使其在php版本中工作< 5.3

  

私有函数GetShape($ type){

    switch($type) {

        case 'side':

            $shape_id = hexdec(substr($this->_hash, 22, 1)) & (sizeof($this->_shapesSide) - 1);

            $shapes = $this->_shapesSide;
        break;
        case 'center':
            $shape_id = hexdec(substr($this->_hash, 23, 1)) & (sizeof($this->_shapesCenter) - 1);

            $shapes = $this->_shapesCenter;
        break;

        case 'corner':
            $shape_id = hexdec(substr($this->_hash, 24, 1)) & (sizeof($this->_shapesCorner) - 1);

            $shapes = $this->_shapesCorner;
        default:
        break;

    }

    $shape = $shapes[$shape_id];

    array_walk($shape, function(&$coord, $index, $mult) { $coord *= $mult; }, self::SPRITE_SIZE);
    return $shape;

}

3 个答案:

答案 0 :(得分:7)

直到PHP 5.3才引入

Closures

由于您运行的是PHP 5.2.17,因此需要重写array_walk()以使用create_function()(如文档所示)。

array_walk(
  $shape,
  create_function('&$coord, $index, $mult', '$coord *= $mult'),
  self::SPRITE_SIZE
);

注意: 我在你没有使用$index 时压缩了这个函数。忘了这是一个回调,所以参数很重要。

请考虑更新至至少 PHP 5.3。

答案 1 :(得分:5)

只需执行以下操作

array_walk(
    $shape,
    create_function(
        '&$coord, $index, $mult',
        '$coord *= $mult;'
    ),
    self::SPRITE_SIZE
);

我在php<测试了avatarico 5.3并且它有效!

答案 2 :(得分:3)

如果你低于PHP 5.3

,你也可以这样使用array_walk回调函数
function array_walk_callback(&$coord, $mult){
   $coord *= $mult;
}

array_walk($shape, 'array_walk_callback', self::SPRITE_SIZE);