简体   繁体   English

PHP这段代码的语法有什么问题?

[英]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. 我在php中建立一些简单的验证规则,而我的IDE(phped)抱怨语法。

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' phped抱怨“意外的回报”

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. 您不能在三元运算符中使用return。 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: GSto的答案似乎是最好的,尽管您可能还想查看php的empty函数:

http://www.php.net/empty http://www.php.net/empty

strlen() returns 0 when the string is empty, and in PHP 0==false . 当字符串为空时, strlen()返回0,而在PHP中, 0==false So really, it's unnecessary to wrap strlen() in a function. 因此,实际上,没有必要将strlen()包装在函数中。 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块中调用),则只需

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM