PHP and undefined variables strategy

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

提交回复
热议问题