是`和'最佳实践

时间:2012-10-06 10:35:44

标签: php syntax

我在http://www.php.net/manual/en/function.str-split.php#78040

看到了这个脚本
   /**
     Returns a formatted string based on camel case.
     e.g. "CamelCase" -> "Camel Case".
    */
    function FormatCamelCase( $string ) {
            $output = "";
            foreach( str_split( $string ) as $char ) {
                    strtoupper( $char ) == $char and $output and $output .= " ";
                    $output .= $char;
            }
            return $output;
    }

古玩部分是:

strtoupper( $char ) == $char and $output and $output .= " ";

我的问题

  • 详细分析strtoupper( $char ) == $char and $output and $output .= " ";及其有效原因
  • 这不适用于breakreturnecho但适用于任何功能,包括print
  • 这是最佳实践
  • 这样的代码有任何优点或缺点

5 个答案:

答案 0 :(得分:4)

相同
if (strtoupper( $char ) == $char) {
    if ($output) {
         $output .= " ";
    }  
}

对于代码A and B,如果将B评估为true,则会执行A

&&and之间的差异&&优先级高于and.=介于它们之间。

答案 1 :(得分:4)

http://en.wikipedia.org/wiki/Short-circuit_evaluation

正如其他答案所示,只有前面的语句== true。

才会执行每个后续语句

这在代码中更相关:if(foo and bar){// do something}

如果foo == false,则无需浪费时间评估吧。

我不能说我在布尔逻辑之外使用短路评估,并且为了查看我的代码的其他编码员,我现在可能不会开始。

答案 2 :(得分:1)

  strtoupper( $char ) == $char and $output and $output .= " ";

如果首先检查它是否为大写字符,如果是这样,他会转到下一个并检查$output是否为空,然后他为$ output添加空格

这不是最好的做法,但使用一个衬垫感觉很酷

优点是它很酷 缺点是你需要一遍又一遍地阅读它才能理解它

答案 3 :(得分:0)

strtoupper($ char)== $ char和$ output and $ output。=" &#34 ;;

装置

if(strtoupper( $char ) == $char && $output && $output.=" "){
// if string is equal than it checks for $output
//is that present?
// if  present than it checks for $output value
//and add a space to that if everything works fine than go to true part
}

答案 4 :(得分:0)

这里有一个表达式,它由三个与逻辑and运算符连接的子表达式组成:

       strtoupper( $char ) == $char and $output and $output .= " ";
                             A      and    B    and       C

由于运算符优先级,顺序从左到右是直接的。

因为那样,你可以通过。我想你明白A和B和C在它自己的作用。但是,如果这三个中的任何一个将评估为false,则退出执行整个表达式。该表达式一直运行直到false被执行(否则PHP无法说明结果,请参阅Short-circuit evaluation)。

它显示:字符为大写并输出并添加空格以输出。

如果字符不是大写,则该句子是错误的。所以它不会持续超过:

它的内容是:字符不是大写字母。

让我们把句子说成是大写字母。但没有输出:

它显示:字符是大写的,没有输出。

最后让我们说有输出:

它显示:字符为大写并输出并添加空格以输出。

将编程语言看作是用语言表达的语言。

这只是一个常见的表达方式。一些程序员不习惯用它来编写表达的表达,在他们的心智模型中,它更像是基本的,就像其他的写作风格一样:

if (A) then if (b) then C.

它显示:如果字符是大写,那么如果输出则添加一个空格来输出。

做最适合你的事。然后阅读代码。它有所帮助:

strtoupper( $char ) == $char and $output and $output .= " ";

字符为大写并输出并添加空格以输出。