php - 多次调用 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>";
解决方案
您不应该在其他命名函数中声明命名函数。这样做意味着每次调用外部函数时都要重新声明内部函数。将内部函数移出。
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>";
推荐阅读
- python - Selenium 与 Python:如何在具有已知类的元素中选择标签
- python - 使用 Webargs Flaskparser 验证 URL 路径和查询参数中的变量参数
- python - 在 tkinter 计算器中显示减号和加号
- node.js - 在网页上发送 Apache Kafka 数据
- http-headers - 如何让浏览器将所有 HTTP 标头传递给 ServiceWorker?
- python - 在python中对导入语句进行分组
- javascript - 如何在 Express 中使用 Handlebars?
- python - 当我检查硬退回电子邮件时,python 上的条件
- android - 从 React Native 项目生成 apk 时遇到问题?
- vue.js - 无法在控制台中输出全局属性