簡體   English   中英

是最佳實踐

[英]Is `and` best practice

我在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 .= " ";的詳細細分strtoupper( $char ) == $char and $output and $output .= " "; 以及為什么它有效
  • 這對於breakreturnecho無效,但對包括print在內的任何功能均有效
  • 這是最佳做法嗎
  • 這樣的代碼有什么優點或缺點嗎

與...相同

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

對於代碼A and B ,如果A評估為true,則將執行B

&&and與之間的區別是&&優先級高於and .=之間的區別。

http://zh.wikipedia.org/wiki/短路評估

正如其他答案所表明的那樣,每個后續語句僅在前面的語句== true時才執行。

這在諸如以下代碼中更相關:if(foo和bar){//做某事}

如果foo == false,則無需浪費時間評估bar。

我不能說我使用短路評估來獲得布爾邏輯之外的優勢,並且為了其他編碼人員查看我的代碼,我現在可能不會開始。

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

如果首先檢查它是否是大寫字符,則是一種簡寫形式,如果是,則轉到下一個並檢查$output是否為空,然后在$ output中添加一個空格

這不是最佳實踐,但使用一根襯管感覺很酷

優點是它很酷缺點是您需要反復閱讀以了解它

strtoupper($ char)== $ char以及$ output和$ output。=“”;

手段

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
}

您在這里有一個表達式,該表達式由三個子表達式組成,這些子表達式與邏輯and運算符連接在一起:

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

由於運算符的優先級,順序是從左到右的。

因為那是您只需經歷。 我認為您了解A,B和C本身的作用。 但是,如果這三個函數中的任何一個,PHP都將評估為false退出執行整個表達式。 該表達式一直運行到執行false為止(否則,PHP無法說出結果,請參閱“ 短路評估” )。

它顯示為:字符為大寫並輸出,並在輸出處添加一個空格。

如果字符不是大寫,則該句子是錯誤的。 因此,持續時間不會超過:

它顯示為:字符不是大寫。

讓我們用這個句子說這個字符是大寫的。 但沒有輸出:

它顯示為:字符為大寫且無輸出。

最后,我們說一下輸出:

它顯示為:字符為大寫並輸出,並在輸出處添加一個空格。

可以將編程語言視為表達某些內容的語言。

這只是一個普通的表達。 一些程序員不習慣於編寫表達性的表達式,在他們的思維模型中,它更基本,就像其他寫作風格一樣:

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

它顯示為:如果字符是大寫字母,則如果輸出,則在輸出處添加一個空格。

做最適合您的事情。 並閱讀代碼。 它有助於:

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

字符為大寫並輸出,並為輸出添加空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM