[英]How to read spagetti php shorthand if statement ( ternary operators) and conver it into if and else statement
有人寫了這個“驚人的”簡短的簡短陳述。 我確信它甚至都不打算這樣做,但我想將其分解為其他人(也包括我自己),以便通過將其分解為if和else語句來更好地理解它。 我想知道將其分解的確切方式是什么。 ? 和:位置真的讓我感到困惑,讓我無所適從! (即有一個又一個?那怎么可能?
$cust->is_company() ? 'TekCustomer__'.($cust->getID() ? $cust->getID() : 'new'.($next_new_id-1)) : 'Person__'.($cust->people[0]->getID() ? $cust->people[0]->getID() : 'new'.$next_new_id++)
您可能會發現它更像這樣可讀:
$cust->is_company() ?
'TekCustomer__' . ( $cust->getID() ? $cust->getID() : 'new'.($next_new_id-1) )
:
'Person__' . ( $cust->people[0]->getID() ? $cust->people[0]->getID() : 'new'.$next_new_id++)
基本上,它檢查它是否是一家公司 :
TekCustomer__
。 如果不是,它似乎會生成一個新的ID。 Person__
。 如果不是,它似乎會生成一個新的ID。 這可能是應該擴展的方式。 它稱為三元運算符。
$statement ? value_if_true : value_if_false
$statement ? value_if_true : value_if_false
。
if($cust->is_company())
{
$string = 'TekCustomer__';
if($cust->getId())
{
$string .= $cust->getID();
}
else
{
$string .= 'new'.($next_new_id-1));
}
}
else
{
$string = 'Person__';
if($cust->people[0]->getID())
{
$string .= $cust->people[0]->getID();
}
else
{
$string .= 'new'.$next_new_id++;
}
}
我強烈建議您不要使用嵌套三元運算符。 如您所知,它們遠非易讀。 轉換為適當的if語句肯定會使它更具可讀性。 我們可以先將其格式化以幫助分解它:
$cust->is_company() ?
'TekCustomer__'.($cust->getID() ? $cust->getID() : 'new'.($next_new_id-1)) :
'Person__'.($cust->people[0]->getID() ? $cust->people[0]->getID() : 'new'.$next_new_id++)
啊哈! 實際上,它並沒有像它最初看起來那樣可怕(特別是由於PHP在嵌套三元數上的奇怪行為)。
首先,它檢查$cust->is_company()
並執行以下兩項操作之一。 這給我們:
if($cust->is_company()){
'TekCustomer__'.($cust->getID() ? $cust->getID() : 'new'.($next_new_id-1));
}else{
'Person__'.($cust->people[0]->getID() ? $cust->people[0]->getID() : 'new'.$next_new_id++)
}
請注意,通常您會使用這些值。 這將取決於表達式最初的使用方式。
我將把內部三元數留給讀者練習!
* PHP從左到右而不是從右到左解析嵌套的三元運算符。 參見http://php.net/manual/en/language.operators.comparison.php
我不知道每個變量的含義,但這是一種解構它的方法。
if($cust->is_company())
{
echo 'TekCustomer__';
if($cust->getID())
{
echo $cust->getID();
}else
{
echo 'new'.$next_new_id-1;
}
}else
{
echo 'Person__';
if($cust->people[0]->getID())
{
echo $cust->people[0]->getID();
}else
{
echo 'new'.$next_new_id++;
}
}
if ($cust->is_company())
if ($cust->getID())
return 'TekCustomer__' . $cust->getID();
else
return 'TekCustomer__new'.($next_new_id-1);
else
if ($cust->people[0]->getID())
return 'Person__' . $cust->people[0]->getID();
else
return 'Person__new'.$next_new_id++);
看起來這是作業右側的聲明。 因此,我們需要一個變量來構建字符串,然后用括號將其分解:
$tmp = '';
if ($cust->is_company()) { // first '?'
$tmp .= 'TekCustomer__';
if ($cust->getID()) { // second '?'
$tmp .= $cust->getID();
} else {
$tmp .= 'new' . ($next_new_id - 1);
}
} else {
$tmp .= 'Person__';
if ($cust->people[0]->getID()) { // third '?'
$tmp .= $cust->people[0]->getID();
} else {
$tmp .= 'new' . $next_new_id++;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.