Programming

if () {}와 if ()의 차이점 : endif;

procodes 2020. 6. 9. 22:51
반응형

if () {}와 if ()의 차이점 : endif;


차이점이 있습니까?

if ($value) {

}

...과...

if ($value):

endif;

?


그것들은 동일하지만 두 번째 코드는 코드에 MVC가 있고 코드에 많은 에코를 원하지 않는 경우 좋습니다. 예를 들어 내 .phtml파일 (Zend Framework)에서 다음과 같이 작성합니다.

<?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>

나는 개인적으로 대체 구문을 정말 싫어합니다. 중괄호에 대한 한 가지 좋은 점은 대부분의 IDE, vim 등이 모두 대괄호 강조 표시라는 것입니다. 내 텍스트 편집기에서 괄호를 두 번 클릭하면 청크 전체가 강조 표시되어 어디서 끝나고 쉽게 시작되는지 확인할 수 있습니다.

endif, endforeach 등을 강조 표시 할 수있는 단일 편집기를 모르겠습니다.


나는 이것이 모든 것을 말한다고 생각한다.

이 대안 구문은 혼합 된 상황에서 가독성을 향상시키는 데 탁월합니다 (PHP 및 HTML 모두에 대해!).

http://ca3.php.net/manual/en/control-structures.alternative-syntax.php

HTML과 PHP를 혼합 할 때 대체 sytnax를 훨씬 쉽게 읽을 수 있습니다. 일반적인 PHP 문서에서는 전통적인 구문을 사용해야합니다.


회사에서 HTML을 처리하는 기본 방법은 다음과 같습니다.

<? if($condition) { ?>
   HTML content here
<? } else { ?>
   Other HTML content here
<? } ?>

결국, 그것은 실제로 하나를 선택하고 고집하는 문제입니다.


그것들은 실제로 기능적으로 동일합니다.

그러나 endif통신원으로부터 너무 멀어지면 if참조 의견을 제시하는 것이 훨씬 좋습니다. 열린 위치를 쉽게 찾을 수 있습니다. 어떤 언어인지에 관계없이 :

if (my_horn_is_red or her_umbrella_is_yellow)
{

    // ...

    // let's pretend this is a lot of code in the middle

    foreach (day in week) {
        sing(a_different_song[day]);
    }

    // ...

} //if my_horn_is_red

그것은 실제로 모든 유사한 "닫는 것"에 적용됩니다! ;)

또한 일반적으로 편집자는 중괄호를 더 잘 다루므로 열린 위치를 가리킬 수 있습니다. 그렇다고해서 설명적인 주석이 덜 유효한 것은 아닙니다.


공식 문서에서 찾을 수 있습니다. PHP : 제어 구조의 대체 구문


뷰 스크립트에서 ifs, fors 및 foreaches 를 함께 사용할 때 특히 명확하다고 생각합니다 .

<?php if ( $this->hasIterable ): ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ):?>
        <?php for ( $i = 0; $i <= $val; $i++ ): ?>
        <li><?php echo $key ?></li>
        <?php endfor; ?>
    <?php endforeach; ?>
    </ul>
<?php elseif ( $this->hasScalar ): ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ): ?>
    <p>Foo = Bar</p>
    <?php endfor; ?>
<?php else: ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ): ?>
    <p>Spam</p>
    <?php else: ?>  
    <p>Eggs</p>  
    <?php endif; ?>
<?php endif; ?>

반대로 :

<?php if ( $this->hasIterable ){ ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ){?>
        <?php for ( $i = 0; $i <= $val; $i++ ){ ?>
        <li><?php echo $key ?></li>
        <?php } ?>
    <?php } ?>
    </ul>
<?php } elseif ( $this->hasScalar ){ ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ){ ?>
    <p>Foo = Bar</p>
    <?php } ?>
<?php } else { ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ){ ?>
    <p>Spam</p>
    <?php } else { ?>  
    <p>Eggs</p>  
    <?php } ?>
<?php } ?>

이것은 특히 중괄호에서 상단 선언을 볼 수없는 긴 제어문에 유용합니다.


나는 그것이 당신의 개인 코딩 스타일에 달려 있다고 생각합니다. C ++, Javascript 등에 익숙하다면 {} 구문을 사용하는 것이 더 편할 것입니다. Visual Basic에 익숙하다면 if : endif; 통사론.

I'm not sure one can definitively say one is easier to read than the other - it's personal preference. I usually do something like this:

<?php
if ($foo) { ?>
   <p>Foo!</p><?php
} else { ?>
   <p>Bar!</p><?php
}  // if-else ($foo) ?>

Whether that's easier to read than:

<?php
if ($foo): ?>
   <p>Foo!</p><?php
else: ?>
   <p>Bar!</p><?php
endif; ?>

is a matter of opinion. I can see why some would feel the 2nd way is easier - but only if you haven't been programming in Javascript and C++ all your life. :)


I would use the first option if at all possible, regardless of the new option. The syntax is standard and everyone knows it. It's also backwards compatible.


Both are the same.

But: If you want to use PHP as your templating language in your view files(the V of MVC) you can use this alternate syntax to distinguish between php code written to implement business-logic (Controller and Model parts of MVC) and gui-logic. Of course it is not mandatory and you can use what ever syntax you like.

ZF uses that approach.


There is no technical difference between the two syntaxes. The alternative syntax is not new; it was supported at least as far back as PHP 4, and perhaps even earlier.

You might prefer the alternative form because it explicitly states which control structure is ending: endwhile, for example, can only terminate a while block, whereas if you encounter a brace, it could be closing anything.

You might prefer the traditional syntax, though, if you use an editor that has special support for braces in other C-like syntaxes. Vim, for example, supports several keystrokes for navigating to matching braces and to the starts and ends of brace-delimited blocks. The alternative syntax would break that editor feature.


In the end you just don't want to be looking for the following line and then having to guess where it started:

<?php } ?>

Technically and functionally they are the same.


It all depends, personally I prefer the traditional syntax with echos and plenty of indentations, since it's just so much easier to read.

<?php
    if($something){
        doThis();
    }else{
        echo '<h1>Title</h1>
            <p>This is a paragraph</p>
            <p>and another paragraph</p>';
    }
?>

I agree alt syntax is cleaner with the different end clauses, but I really have a hard time dealing with them without help from text-editor highlighting, and I'm just not used to seeing "condensed" code like this:

<?php if( $this->isEnabledViewSwitcher() ): ?>
<p class="view-mode">
    <?php $_modes = $this->getModes(); ?>
    <?php if($_modes && count($_modes)>1): ?>
    <label><?php echo $this->__('View as') ?>:</label>
    <?php foreach ($this->getModes() as $_code=>$_label): ?>
        <?php if($this->isModeActive($_code)): ?>
            <strong title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></strong>&nbsp;
        <?php else: ?>
            <a href="<?php echo $this->getModeUrl($_code) ?>" title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></a>&nbsp;
        <?php endif; ?>
    <?php endforeach; ?>
    <?php endif; ?>
</p>
<?php endif; ?>

I used to use the curly braces but now a days I prefer to use this short-hand alternative syntax because of code readability and accessibility.


Personally I prefer making it in two seperate sections but within the same PHP like:

<?php 
    if (question1) { $variable_1 = somehtml; }
    else { $variable_1 = someotherhtml; } 

    if (question2) {
        $variable_2 = somehtml2;
    }

    else { 
        $variable_2 = someotherhtml2;
    }         

etc.
$output=<<<HERE
htmlhtmlhtml$variable1htmlhtmlhtml$varianble2htmletcetcetc
HERE;
echo $output;

?>

But maybe it is slower?


I think it's a matter of preference. I personally use:

if($something){
       $execute_something;
}

I used to use curly brackets for "if, else" conditions. However, I found "if(xxx): endif;" is more semantic if the code is heavily wrapped and easier to read in any editors.

Of course, lots editors are capable of recognise and highlight chunks of code when curly brackets are selected. Some also do well on "if(xxx): endif" pair (eg, NetBeans)

Personally, I would recommend "if(xxx): endif", but for small condition check (eg, only one line of code), there are not much differences.


I feel that none of the preexisting answers fully identify the answer here, so I'm going to articulate my own perspective. Functionally, the two methods are the same. If the programer is familiar with other languages following C syntax, then they will likely feel more comfortable with the braces, or else if php is the first language that they're learning, they will feel more comfortable with the if endif syntax, since it seems closer to regular language.

If you're a really serious programmer and need to get things done fast, then I do believe that the curly brace syntax is superior because it saves time typing

if(/*condition*/){
    /*body*/ 
}

compared to

if(/*condition*/):
    /*body*/
endif;

This is especially true with other loops, say, a foreach where you would end up typing an extra 10 chars. With braces, you just need to type two characters, but for the keyword based syntax you have to type a whole extra keyword for every loop and conditional statement.

참고URL : https://stackoverflow.com/questions/564130/difference-between-if-and-if-endif

반응형