首页 > 解决方案 > 多次调用 PHP 函数

问题描述

我的 php 脚本失败。可能是什么问题呢?

注意:我需要在同一页面上多次调用该函数。

错误:致命错误:无法在第 6 行的 D:\vhosts\xyz.php 中重新声明 countLetters()(之前在 D:\vhosts\xyz.php:6 中声明)

function testfunction($str) {
 $pattern = '/[a-z0-9\.]+/i';
 function countLetters($matches) {
   return $matches[0] . '(' . strlen($matches[0]) . ')';
 }
 return preg_replace_callback($pattern, 'countLetters', $str);
}
echo testfunction("Hello world")."<br>";
echo testfunction("Life is good")."<br>";
echo testfunction("I love you")."<br>";

标签: phpfunction

解决方案


您不应该在其他命名函数中声明命名函数。这样做意味着每次调用外部函数时都要重新声明内部函数。将内部函数移出。

function testfunction($str) {
 $pattern = '/[a-z0-9\.]+/i';

 return preg_replace_callback($pattern, 'countLetters', $str);
}

 function countLetters($matches) {
   return $matches[0] . '(' . strlen($matches[0]) . ')';
 }
echo testfunction("Hello world")."<br>";
echo testfunction("Life is good")."<br>";
echo testfunction("I love you")."<br>";

推荐阅读