create_function instead of lambda-function avartaco


create_function instead of lambda-function avartaco

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

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

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

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

并重写它以使用 create_function() 而不是 lambda 函数。

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

那么我应该在该行中更改什么才能使其在 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;
    
}

直到 PHP 5.3 才引入闭包。

由于您运行的是 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。

只需执行以下操作

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

我已经在 php <5.3 中测试了头像,它可以工作!

或者,如果您低于 PHP 5.3 array_walk也可以以这种方式使用回调函数

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