调用common.php中printRightContent函数时出现PHP未定义函数错误
问题场景
在Adcovate.php中尝试调用根目录下lib/common.php里的printRightContent()函数时,触发以下错误:
PHP Fatal error: Uncaught Error: Call to undefined function printRightContent()
用户代码如下:
Adcovate.php
<?php include 'lib/common.php'; function printResults($page, $perpage) { ?> <div id="right_content"> <?php error_reporting(E_ALL); ini_set('log_errors', 1); ini_set('error_log', 'hey_this_errors.log'); printRightContent(); ?> </div> <?php } ?>
common.php
<?php /* Optimize site using GZIP Compression also see .htaccess */ echo "<script>console.log('Common library checkpoint#1' );</script>"; if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start(); ?> <?php /* dirty code */ define("WEBNAME", "Lawyers.com"); function printRightContent() { echo "<script>console.log('Common library checkpoint#2' );</script>"; -------somework----- }?>
用户尝试排查后还遇到浏览器警告:crbug/1173575, non-JS module files deprecated.,但核心的函数未定义问题仍未解决。
解决方案
1. 修复文件引入路径问题
最可能的原因是include 'lib/common.php';的相对路径不正确。如果Adcovate.php不在根目录下,相对路径会找不到common.php。换成绝对路径即可:
include $_SERVER['DOCUMENT_ROOT'] . '/lib/common.php';
或者根据Adcovate.php的实际位置调整相对路径,比如如果Adcovate.php在根目录的某个子文件夹里,用include '../lib/common.php';。
2. 验证common.php是否被正确加载
在Adcovate.php的include语句后添加检查,确认文件是否成功加载:
include 'lib/common.php'; // 检查文件是否存在并加载 if (!function_exists('printRightContent')) { die('common.php未正确加载,或printRightContent函数未定义'); }
同时看浏览器控制台是否输出Common library checkpoint#1,如果没输出,说明common.php根本没被加载,路径肯定错了。
3. 排查common.php的语法错误
common.php里的-------somework-----是占位符,实际代码如果有语法错误(比如括号不匹配、缺少分号、关键字错误),会导致函数printRightContent()无法被正确定义。可以单独运行common.php,或者开启PHP的语法错误提示,检查是否有语法问题。
4. 关于crbug浏览器警告
这个警告是Chrome浏览器的内部提示,和PHP代码无关,是浏览器对非JS模块文件加载方式的废弃提醒,不会影响PHP函数调用,无需处理。
内容的提问来源于stack exchange,提问作者Anirudh Rawat

