1

こんにちは、私は最近、ショッピング カートのページネーター クラスを調べていて、コードを理解しようとして、次のコード行に出くわしたときに独自のページネーターを作成できるようにしました。三項ステートメントに似ていますが、これまでに見たことのない方法で書かれています。私はそれをグーグルで検索しますが、何をグーグルで検索すればよいかわかりません。これがどのように機能し、何と呼ばれているのか誰か教えてください。検索して詳細を知ることができます。

    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>';

これが続行するのに十分なコードかどうか教えてください ありがとうアンドリュー

4

3 に答える 3

2

いいですね...これは単なる通常の条件演算子です(まあ、そのうちの3つといくつかの連結があります)。

再フォーマットすると、少し明確になります。

$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;
于 2009-12-02T10:54:59.657 に答える
1

これは条件演算子と呼ばれ、これは悪用だと思います。条件演算子は、コードの可読性に影響を与えることなく、短いif-else構文を1つのステートメントに減らすのに役立ちます。

if(a == b)
    c = d;
else
    c = e;
//can be written as:
c = a == b ? d : e;

指定されたコードは次のように記述できます。

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>';

そして、以下と同等です:

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>';
于 2009-12-02T11:15:56.153 に答える
1
expression ? runs if true : runs if false;

詳細はこちら

 http://www.johnhok.com/2008/02/23/php-tip-tertiary-operator/

あなたの場合:

$output ? '<div class="' . $this->style_links . '">' . $output . '</div>' : ''

$output 変数が空でない場合は、以下が返されます。それ以外の場合は、空の '' 文字列が返されます。

<div class="' . $this->style_links . '">' . $output . '</div>'

コードで使用される他の 3 次演算子の場合も同様です。

于 2009-12-02T10:54:16.353 に答える