Weak typing in PHP: why use isset at all?

前端 未结 9 830
孤街浪徒
孤街浪徒 2020-12-01 12:38

It seems like my code works to check for null if I do

if ($tx) 

or

if (isset($tx))

why would I do the se

9条回答
  •  醉梦人生
    2020-12-01 13:26

    I want to point out that everyone's reponse I've read here should have one caveat added:

    "isset() will return FALSE if testing a variable that has been set to NULL" (php.net/isset).

    This means that in some cases, like checking for a GET or POST parameter, using isset() is enough to tell if the variable is set (because it will either be a string, or it won't be set). However, in cases where NULL is a possible value for a variable, which is fairly common when you get into objects and more complex applications, isset() leaves you high and dry.

    For example (tested with PHP 5.2.6 with Suhosin-Patch 0.9.6.2 (cli) (built: Aug 17 2008 09:05:31)):

    outputs:

    bool(true)
    bool(false)
    bool(false)
    

    Thanks, PHP!

提交回复
热议问题