Php ternary statement
Hi i was recently looking over a shopping cart paginator class, trying to understand their code so i could build my own paginator when i came across the following line of code. It resembles a ternary statement but is written in a way that i have never seen before. I would google it but i wouldn't know what to google. Could someone please tell me what this is how it works and what it is called so i can do a search for it and learn more.
return ($output ? '开发者_运维百科<div class="' . $this->style_links . '">' . $output . '</div>' : '')
. '<div class="' . $this->style_results . '">' . sprintf($this->text, ($total) ? (($page - 1) * $limit) + 1 : 0, ((($page - 1) * $limit) > ($total - $limit)) ? $total : ((($page - 1) * $limit) + $limit), $total, $num_pages) . '</div>';
Just let me know if this is enough code to go on Thanks Andrew
Nice... It is just a regular conditional operator (well, 3 of them, along with some concatenation).
If you reformat it, it gets a bit clearer:
$output = $output ? '<div class="' . $this->style_links . '">' . $output . '</div>' : '';
$min = $total ? (($page - 1) * $limit) + 1 : 0;
$max = (($page - 1) * $limit) > ($total - $limit) ? $total : ((($page - 1) * $limit) + $limit);
$output .= '<div class="' . $this->style_results . '">'
. sprintf($this->text, $min, $max, $total, $num_pages)
. '</div>';
return $output;
It is called conditional operator and I would consider this to be an abuse of it. Conditional operators can be useful in reducing short if-else constructs into one statement without effecting the readability of the code.
if(a == b)
c = d;
else
c = e;
//can be written as:
c = a == b ? d : e;
The given code can be written as:
return ($output ?
'<div class="' . $this->style_links . '">' . $output . '</div>'
: '') .
'<div class="' . $this->style_results . '">' .
sprintf($this->text,
($total) ?
(($page - 1) * $limit) + 1
: 0,
((($page - 1) * $limit) > ($total - $limit)) ?
$total
: ((($page - 1) * $limit) + $limit),
$total, $num_pages) . '</div>';
And is equivalent to:
if($output)
$str = '<div class="' . $this->style_links . '">' . $output . '</div>';
else
$str = '';
$str .= '<div class="' . $this->style_results . '">';
if($total)
$first = (($page - 1) * $limit) + 1;
else
$first = 0;
if((($page - 1) * $limit) > ($total - $limit))
$second = $total;
else
$second = ((($page - 1) * $limit) + $limit);
$str .= sprintf($this->text, $first, $second, $total, $num_pages);
$str .= '</div>';
expression ? runs if true : runs if false;
More here
http://www.johnhok.com/2008/02/23/php-tip-tertiary-operator/
In your case:
$output ? '<div class="' . $this->style_links . '">' . $output . '</div>' : ''
If $output variable is not empty then following is return otherwise empty '' string is returned.
<div class="' . $this->style_links . '">' . $output . '</div>'
Same is the case with other tertiary operators used in your code.
精彩评论