douhe2305 2012-04-05 15:09
浏览 67
已采纳

将PHP 5.3中的匿名函数转换为PHP 5.2等效函数

I have error in line 2 and 13 in PHP 5.2, I have no idea to make the correction, I tried using create_function but not working, can anyone help with this?

function _process_special_keyword($str){
   $callback = function($match){
     $ret = $match[1] . '[' . $match[2] . ']';
     if(!empty($match[3])){
       $ret .= '.[' . $match[3] . ']';
     } 
     $ret .= $match[4];
     return $ret;           
   };

   $strSQL = preg_replace_callback('/([\s\(\.,])(' . SPECIAL_KEYWORDS . ')(?:\.(' . SPECIAL_KEYWORDS . '))?([\s\)\.,])/i', $callback, $str);

   $callback = function($match){
     return 'CASE WHEN ' . $match[1] . ' THEN ' . $match[2] . ' ELSE ' . $match[3] . ' END';
   };

   $strSQL = preg_replace_callback('/if\s*\((.+),(.+),(.+)\)/i', $callback, $strSQL);
   return $strSQL;
}

Thanks.

Error: Parse error: syntax error, unexpected T_FUNCTION

  • 写回答

3条回答 默认 最新

  • dongzhuo1880 2012-04-05 15:15
    关注

    You can declare the callbacks outside of this function. Like this:

    function _callback_one($match){
      $ret = $match[1] . '[' . $match[2] . ']';
      if(!empty($match[3])){
        $ret .= '.[' . $match[3] . ']';
      } 
      $ret .= $match[4];
      return $ret;           
    }
    
    function _callback_two($match){
      return 'CASE WHEN ' . $match[1] . ' THEN ' . $match[2] . ' ELSE ' . $match[3] . ' END';
    }
    
    function _process_special_keyword($str){
       $strSQL = preg_replace_callback('/([\s\(\.,])(' . SPECIAL_KEYWORDS . ')(?:\.(' . SPECIAL_KEYWORDS . '))?([\s\)\.,])/i', '_callback_one', $str);
    
       $strSQL = preg_replace_callback('/if\s*\((.+),(.+),(.+)\)/i', '_callback_two', $strSQL);
       return $strSQL;
    }
    

    Note: If these functions are in a class (meaning the function would be need to called like $this->_callback_one), pass an array as the "callback" parameter.

    function _process_special_keyword($str){
       $strSQL = preg_replace_callback('/([\s\(\.,])(' . SPECIAL_KEYWORDS . ')(?:\.(' . SPECIAL_KEYWORDS . '))?([\s\)\.,])/i', array($this, '_callback_one'), $str);
    
       $strSQL = preg_replace_callback('/if\s*\((.+),(.+),(.+)\)/i', array($this, '_callback_two'), $strSQL);
       return $strSQL;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?