开发者

PHP what is wrong with the syntax of this code?

I'm building some simple validation rules in php and my IDE (phped) is complaining about the syntax.

Can anyone tell me what is wrong with the following?

function notBlank($str) {
    (strlen($str) == 0) ? return false : return true;
}

phped complains of 'unexpected return'

开发者_如何转开发

Any advice appreciated.

Thanks.


write it like this:

function notBlank($str){
   return strlen($str) != 0;
}


Write it like this:

function notBlank($str) {
    return ( strlen($str) == 0 ? false : true );
}


You cant use return within ternary operators. If you want to keep that syntax you have to do something like this:

function notBlank($str = '') {
    $var = (strlen($str) == 0) ? false : true;
    return $var;
}

Nevertheless do notice that the default way of doing things is more legible:

function notBlank($str = '') {
    if(strlen($str) == 0)
        return false;
    else
        return true;
}

Hope it helps!


GSto's answer seems the best here, though you might also like to check out php's empty function:

http://www.php.net/empty


strlen() returns 0 when the string is empty, and in PHP 0==false. So really, it's unnecessary to wrap strlen() in a function. If you want to insist on a boolean answer then cast it. ie:

(bool) strlen($string);

So instead of your function, which is assumably called in an if block, you'd just have

if(strlen($string)) //etc.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜