Frage

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 . "\n");
fclose($fd);

My call to the function:

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

Help please?

War es hilfreich?

Lösung

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 . "\n");
        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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top