【问题标题】:Using Anonymous functions in php 5.2在 php 5.2 中使用匿名函数
【发布时间】:2013-09-12 20:12:52
【问题描述】:

我知道只有 php5.3 及以上版本才支持匿名函数。

但由于一些困难的情况,我不得不在php 5.2中使用下面的代码

谁能帮我把它转换成在 php 5.2 中工作

================================================ =====

       $fn = function($points) use ($pdf) {
        $op = 'f';
        $h = $pdf->h;
        $k = $pdf->k;
       $points_string = '';
       for($i=0; $i < 8; $i+=2){
       $points_string .= sprintf('%.2F %.2F', $points[$i]*$k,($h-$points[$i+1])*$k);
            $points_string .= $i ? ' l ' : ' m ';
       }
       $pdf->_out($points_string . $op);
    };

================================================ =====

完整代码见

http://barcode-coder.com/download/php-barcode-2.0.3.zip

我现在已经用 create_function 尝试了几个小时,但不知何故可以让它工作。

请帮我适应php5.2

还有如何复制php5.2中使用的功能

即如何将像 $pdf 这样的 var 传递给 create_function

【问题讨论】:

  • 作为函数参数。

标签: php callback closures anonymous-function


【解决方案1】:

只是将变量作为参数发送:

function fn($points, $pdf) {
        $op = 'f';
        $h = $pdf->h;
        $k = $pdf->k;
       $points_string = '';
       for($i=0; $i < 8; $i+=2){
       $points_string .= sprintf('%.2F %.2F', $points[$i]*$k,($h-$points[$i+1])*$k);
            $points_string .= $i ? ' l ' : ' m ';
       }
       $pdf->_out($points_string . $op);\
};

【讨论】:

    【解决方案2】:
    function whatever($points, $pdf) {
           $op = 'f';
           $h = $pdf->h;
           $k = $pdf->k;
           $points_string = '';
           for($i=0; $i < 8; $i+=2){
           $points_string .= sprintf('%.2F %.2F', $points[$i]*$k,($h-$points[$i+1])*$k);
                $points_string .= $i ? ' l ' : ' m ';
           }
           $pdf->_out($points_string . $op);
    };
    

    然后这样称呼它:

    // your code
    $pdf = new PdfLibraryThing();
    whatever(array('thing'=>'foo','what'=>'stuff'), $pdf);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      相关资源
      最近更新 更多