【问题标题】:PHP: How to make variable visible in create_function()?PHP:如何使变量在 create_function() 中可见?
【发布时间】:2012-04-12 20:30:40
【问题描述】:

这段代码:

$t = 100;
$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/",
                            create_function(
                                  '$matches',
                                  'return $matches[1] + $t;'
                            ), $func);

如何使 $t 在 preg_replace() 函数中的 create_function() 中可见?

【问题讨论】:

  • 你应该使用闭包代替php.net/functions.anonymousfunction($matchtes)use($t){/*..*/}
  • @hakre "1" + 100 ;) 但是我明白了,您的意思是:正则表达式匹配以Name 开头的内容,因此该函数将始终返回100 (=$t)。可能不想要。
  • 解决方案取决于您使用的 PHP 版本。理想情况下,解决方案是使用将 $t 变量传递给use 构造的闭包。这至少需要 PHP 5.3。顺便说一句,如果 $t 的值不是每次都发生变化,您可以考虑使用在任何上下文中都可用的常量。

标签: php preg-replace global-variables preg-replace-callback create-function


【解决方案1】:

anonymous function 可以工作,同时使用 use 语法:

$t = 100;
$str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/",
    function($matches) use($t) // $t will now be visible inside of the function
    {
        return $matches[1] + $t;
    }, $func);

【讨论】:

    【解决方案2】:

    您不能使变量可访问,但在您的情况下,您可以只使用该值:

    $t = 100;
    $str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/",
                                create_function(
                                      '$matches',
                                      'return $matches[1] + ' . $t .';'
                                ), $func);
    

    但是,强烈建议您在此处使用function($matches) use ($t) {} 语法 (http://php.net/functions.anonymous)。

    还有 preg_replace 的 eval 修饰符:

    $str = preg_replace("/(Name[A-Z]+[0-9]*)/e", '$1+'.$t, $func);
    

    但我感觉你的函数在这里使用了错误的运算符 - 或者错误的模式/子模式。

    【讨论】:

      【解决方案3】:

      与让 any 函数看到全局变量的方法相同。

      $str = preg_replace_callback("/(Name[A-Z]+[0-9]*)/",
                                  create_function(
                                        '$matches',
                                        'global $t; return $matches[1] + $t;'
                                  ), $func);
      

      【讨论】:

        【解决方案4】:

        您可以使用$GLOBALS,但不强烈推荐...

        $str = preg_replace_callback ( "/(Name[A-Z]+[0-9]*)/", create_function ( '$matches', 'return $matches[1] + $GLOBALS["t"];' ), $func );
        

        更好的解决方案

        http://php.net/functions.anonymous匿名函数..如果你不喜欢使用它,你也可以在得到数组格式的结果后执行array_walkhttp://php.net/manual/en/function.array-walk.php),然后将$t作为正确的函数传递论据

        【讨论】:

          【解决方案5】:

          在匿名中只需使用关键字 useglobal 在 create_function 中使用 global

          function() 使用($var1,$var2...etc){代码在这里}

          create_func($args,'global $var1,$var2;code here;');

          【讨论】:

          • 当心! global 只从全局作用域导入变量,而不是从定义函数的作用域导入,就像 use 那样。
          猜你喜欢
          • 1970-01-01
          • 2015-10-20
          • 2012-09-12
          • 1970-01-01
          • 1970-01-01
          • 2019-08-29
          • 2014-11-18
          • 2023-04-11
          • 2018-11-02
          相关资源
          最近更新 更多