duanlanzhi5509 2013-11-03 17:25
浏览 11
已采纳

我试图调用一个函数,PHP认为我正在尝试重新声明它

I have a function called "logToFile" and I'm trying to call it but PHP is thinking that I'm trying to redeclare it.

logToFile:

function logToFile($msg) {
$filename = "log.txt";
$fd = fopen($filename, "a");
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
fwrite($fd, $str . "
");
fclose($fd);

My call to the function:

logToFile("$user->username kicked $arg1 for $arg2.");

Help please?

  • 写回答

1条回答 默认 最新

  • dongwu1992 2013-11-03 17:28
    关注

    Well, PHP is not dumb. If PHP says you're re-declaring a function, well, then you are. When the function definition occurs multiple times, PHP will throw a Fatal error, similar to the one below:

    Fatal error: Cannot redeclare logToFile() (previously declared in /path/to/script:X) in /path/to/script on line Y

    Here, X is the line where you originally declared the function, and Y is where you tried to re-declare (not call, as you state in the question) the function. Check your code to find this line, and remove it.

    And to avoid errors like this, you can first check whether a function was defined using function_exists() and then try to declare it:

    if (!function_exists('logToFile')) {
        function logToFile($msg) {
            $filename = "log.txt";
            $fd = fopen($filename, "a");
            $str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
            fwrite($fd, $str . "
    ");
            fclose($fd);
        }
    } else {
        echo 'Trying to re-declare the function';
    }
    

    While the above method will help you avoid fatal errors, I strongly suggest you figure out where you're redefining the function and correct that instead. Most of the times, this will be due to multiple includes of the file containing your function. In that case, you can simply use require_once() instead. PHP will check if the file has already been included, and if so, not include (require) it again.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗