简体   繁体   中英

What kind of syntax is this in PHP?

if(true):
    echo 'good';
endif;

I've only see it in PHP today!

I've always been using:

if(true)
{
   echo 'good';
}

It is the Alternative syntax for control structures .


Quoting that page of the manual :

PHP offers an alternative syntax for some of its control structures; namely, if , while , for , foreach , and switch . In each case, the basic form of the alternate syntax is to change the opening brace to a colon ( : ) and the closing brace to endif; , endwhile; , endfor; , endforeach; , or endswitch; , respectively.


I don't often see it used in "pure PHP" files, but it's quite often used when PHP is mixed with HTML in the same file -- ie when used as a templating language.

You can interlace the former with html very easily.

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

It's exactly the same. I often use such syntax in templates - it's much more readable then (in my opinion). Here's more: Alternative syntax for control structures

The PHP notation:

if(x=1):
  dosomething();
elseif(x=2):
  dosomethingelse();
  andanotherthing();
else:
  doesntmatcheither();
endif;

is also related to

$var=(query?true:false);

or in even more shorthand

$var=query?true:false;

But I personally don't like omitting the parenthesis; call me paranoid ;)

相同的效果,没有区别,并且在我个人看来,提供更好的可读代码和干净的语法,同样类似于结束的关闭关键字可能有助于嵌套控制结构,以指示哪一个正在关闭而不是从一堆大括号中猜测。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM