开发者

PHP - isset($variable) and notices

开发者 https://www.devze.com 2023-01-30 16:30 出处:网络
so if I have th开发者_如何学Pythonis code: $bla = 1; if($foo && $bla) do_whatever... I get a notice telling me that $foo is a undefined variable.

so if I have th开发者_如何学Pythonis code:

$bla = 1;    
if($foo && $bla) do_whatever...

I get a notice telling me that $foo is a undefined variable.

So I have to change my code to this:

$bla = 1;
if(isset($foo) && $foo && $bla) do_whatever...

Is there anyway I can avoid checking if a variable is assigned and just assume the variable is false, but without having to turn off PHP notices?


Depending on the exact behavior you want, you can check if the variable is empty():

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

"" (an empty string) 0 (0 as an integer) "0" (0 as a string) NULL FALSE array() (an empty array) var $var; (a variable declared, but without a value in a class)

It's important to understand all those cases, but it's handy language construct. if $foo is undefined if($foo) will throw a notice, but if(!empty($foo)) will not -- the expression will evaluate to false

This should not be abused, however. As others have stated, those notices are for your protection, so if you can define your variables, you should do so. Where empty() comes in especially handy is things like if (!empty($_GET['foo'])) - testing for the existence of input in superglobals.


The entire point of notices is to tell you that something might be wrong (such as writing $fooo instead of $foo). So, if you're not going to use them, you might as well disable them. You can disable a notice selectively by setting your own error handler, and discarding the error silently when it's of the "undefined variable" kind.

Of course, the clean thing to do would be to define your variables in the first place.


No, there isn't.


No, you should always know exactly what's going on with your variables. In fact, you should never need to use isset() on a variable itself at all.


You could do:

if(@$foo && $bla) do_whatever...

The @ will suppress the warning.

But you really shouldn't do it. Not checking ALL your input is just plain WRONG.

0

精彩评论

暂无评论...
验证码 换一张
取 消