PHP and undefined variables strategy

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

    From what I know the only way to deal with them is to watch the output at execution time.

    Not really: To prevent these notices from popping up, you just need to make sure you initialize variables before accessing them the first time. We (sadly IMO) don't have variable declaration in PHP, but initializing them in the beginning of your code block is just as well:

    $my_var = value;
    

    Using phpDocumentor syntax, you can also kind of declare them to be of a certain a type, at least in a way that many IDEs are able to do code lookup with:

    /** @desc optional description of what the variable does
        @var int */
    $my_var = 0;
    

    Also, you can (and sometimes need to) use isset() / empty() / array_key_exists() conditions before trying to access a variable.

    I agree this sucks big time sometimes, but it's necessary. There should be no notices in finished production code - they eat up performance even if displaying them is turned off, plus they are very useful to find out typos one may have made when using a variable. (But you already know that.)

提交回复
热议问题