PHP and undefined variables strategy

前端 未结 12 1230
名媛妹妹
名媛妹妹 2021-01-17 09:49

I am a C++ programmer starting with PHP. I find that I lose most of the debugging time (and my selfesteem!) due to undefined variables. From what I know, the only way to dea

12条回答
  •  无人及你
    2021-01-17 10:27

    During development stages use

    error_reporting(E_ALL);
    

    which will show every error that has caused, all NOTICE errors, etc.

    Keep an eye on your error_log as well. That will show you errors.

    Use an error reporting system, example:

    http://php.net/manual/en/function.set-error-handler.php

    class ErrorReporter
    {
        public function catch($errno, $errstr, $errfile, $errline)
        {
            if($errno == E_USER_NOTICE && !defined('DEBUG'))
            {
                // Catch all output buffer and clear states, redirect or include error page.
            }
        }
    }
    
    set_error_handler(array(new ErrorReporter,'catch'));
    

    A few other tips is always use isset for variables that you may / may not have set because of a if statement let’s say.

    Always use if(isset($_POST['key'])) or even better just use if(!empty($_POST['key'])) as this checks if the key exists and if the value is not empty.

    Make sure you know your comparison operators as well. Languages like C# use == to check a Boolean state whereas in PHP to check data-types you have to use === and use == to check value states, and single = to assign a value!

提交回复
热议问题