简体   繁体   中英

get rid of "Warning: Undefined variable" warnings in php

How do you get rid of undefined variable warnings in PHP? If you change the error reporting levels

<?php
error_reporting(0)
?>

it will still show up.

I know you can do it with functions

function var_value(&$var) {
    return isset($var) ? $var : false;
}

but it seems really annoying just to use a function var_value($_GET['id']) to get a variable.

I am using PHP 8.1

The Solution (Probably) No One Knows In PHP 8.1

Of course, there is a way to fix this.

The set_error_handler() function.

I have set .htaccess to use auto_prepend_file , let's say, C:\Apache24\code\prepend\index.php . That file will prepend the other files.

index.php

<?php
require_once("handle_err.php");
?>

handle_err.php

<?php
function getErrorType($errno) {
    switch ($errno) {
        case E_NOTICE:
        case E_USER_NOTICE:
            $type = "Notice";
            break;
        case E_WARNING:
        case E_USER_WARNING:
            $type = "Warning";
            break;
        case E_ERROR:
        case E_USER_ERROR:
            $type = "Fatal Error";
            break;
        case E_DEPRECATED:
        case E_USER_DEPRECATED:
            $type = "Deprecated";
            break;
        default:
            $type = "Unknown";
            break;
    }
    return $type;
}

function handleError($errno, $errstr, $errfile, $errline) {
    $errtype = getErrorType($errno);
    if (strpos(strtolower($errstr), "undefined") !== false) {
        return false;
    }
    echo "<p style=\"font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;\"><strong";
    if ($errtype == "Fatal Error") {
        echo " style='color:red'";
    } elseif ($errtype == "Warning") {
        echo " style='color:orange'";
    } elseif ($errtype == "Notice") {
        echo " style='color:blue'";
    } elseif ($errtype == "Deprecated") {
        echo " style='color:grey'";
    } else {
        echo " style='color:black'";
    }
    echo ">$errtype:</strong> $errstr at file $errfile of line $errline";
    if ($errtype == "Fatal Error") {
        exit;
    }
}
set_error_handler('handleError');
?>

What stops the undefined variable warning is the strpos($errstr, 'undefined) !== false' condition. It searches for undefined, if it finds it, it doesn't display the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM