PHP and undefined variables strategy

前端 未结 12 1090
名媛妹妹
名媛妹妹 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:23

    Just watch not to do operations that requires the variable value when using it the first time, like the concatenate operator, .=.

    If you are a C++ programmer you must be used to declare all variables. Do something similar to this in PHP by zeroing variables or creating empty array if you want to use them.

    Pay attention to user input, and be sure you have registered globals off and check inputs from $_GET and $_POST by isset().

    You can also try to code classes against structural code, and have every variable created at the beginning of a class declaration with the correct privacy policy.

    You can also separate the application logic from the view, by preparing all variables that have to be outputted first, and when it goes to display it, you will be know which variables you prepared.

    0 讨论(0)
  • 2021-01-17 10:24

    If you want to hide the error of an undefined variable, then use @. Example: @$var

    0 讨论(0)
  • 2021-01-17 10:25

    Log your E_NOTICE messages to a text file. You can then process logs with automated scripts to indicate files and lines where these are raised.

    0 讨论(0)
  • 2021-01-17 10:26

    No. In PHP, you can only know a variable doesn't exist when you try to access it.

    Consider:

    if ($data = file('my_file.txt')) {
        if (count($data) >= 0)
            $line = reset($data);
    }
    var_dump($line);
    

    You have to restructure your code so that all the code paths leads to the variable defined, e.g.:

    $line = "default value";
    if ($data = file('my_file.txt')) {
        if (count($data) >= 0)
            $line = reset($data);
    }
    var_dump($line);
    

    If there isn't any default value that makes sense, this is still better than isset because you'll warned if you have a typo in the variable name in the final if:

    $line = null;
    if ($data = file('my_file.txt')) {
        if (count($data) >= 0)
            $line = reset($data);
    }
    if ($line !== null) { /* ... */ }
    

    Of course, you can use isset1 to check, at a given point, if a variable exists. However, if your code relies on that, it's probably poorly structured. My point is that, contrary to e.g. C/Java, you cannot, at compile time, determine if an access to a variable is valid. This is made worse by the nonexistence of block scope in PHP.

    1 Strictly speaking, isset won't tell you whether a variable is set, it tell if it's set and is not null. Otherwise, you'll need get_defined_vars.

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2021-01-17 10:29

    Unless I'm missing something, then why is no one suggesting to structure your page properly? I've never really had an ongoing problem with undefined variable errors.

    An idea on structuring your page

    Define all your variables at the top, assign default values if necessary, and then use those variables from there. That's how I write web pages and I never run into undefined variable problems.

    Don't get in the habit of defining variables only when you need them. This quickly creates spaghetti code and can be very difficult to manage.

    alt text

    No one likes spaghetti code

    If you show us some of your code we might be able to offer suggestions on how you can better structure it to resolve these sorts of errors. You might be getting confused coming from a C background; the flow may work differently to web pages.

    0 讨论(0)
提交回复
热议问题