PHP流程控制的替代语法

PHP流程控制的替代语法(The alternative syntax of the PHP process control)早在PHP 4.时代就已存在,只是不见有太多的使用罢了。
##
那么,PHP中哪些语法有替代语法?

##
针对流程控制语句,包括if,while,for,foreach和switch这几个语句有替代语法。

替代语法的基本形式

##
左花括号({)换成冒号(:),把右花括号(})分别换成 endif;,endwhile;,endfor;,endforeach; 以及 endswitch;
##

应用

典型情况下,在纯PHP代码中一般不使用上述替代语法形式,以便与其他流行语句尽量保持一致的可读性原因所致吧。但是,在网页语言中,当你使用PHP开发时,就会经常见到流程语句的替代语法形式了。
也就是说,这些语法能发挥的地方是在PHP和HTML混合页面的代码里面。好处如下:

1.使HTML和PHP混合页面代码更加干净整齐。

有代码洁癖的朋友最惧怕的就是乱七八糟的混合代码,有了这些没有花括号的替代语法,各位爱干净的朋友开心到尿震。

2.流程控制逻辑更清晰,代码更容易阅读

要改别人的PHP和HTML混合代码,打开发现,我擦!太TMD垃圾了!如果用替代语法,我想再垃圾的程序开发人员也不至于写的太乱吧。

3.一些从ASP等其他类basic语言家族转来的朋友,会更容易使用PHP。

##
一个典型的例子是在WordPress网站代码中,你会经常见到。举例如下:

<?php
/**
 * The template for displaying the header
 *
 * Displays all of the head element and everything up until the "site-content" div.
 *
 * @package WordPress
 * @subpackage Twenty_Fifteen
 * @since Twenty Fifteen 1.0
 */
?><!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js">
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width">
    <link rel="profile" href="http://gmpg.org/xfn/11">
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
    <!--[if lt IE 9]>
    <script src="<?php echo esc_url( get_template_directory_uri() ); ?>/js/html5.js"></script>
    <![endif]-->
    <?php wp_head(); ?>
</head>

<body <?php body_class(); ?>>
<div id="page" class="hfeed site">
    <a class="skip-link screen-reader-text" href="#content"><?php _e( 'Skip to content', 'twentyfifteen' ); ?></a>

    <div id="sidebar" class="sidebar">
        <header id="masthead" class="site-header" role="banner">
            <div class="site-branding">
                <?php
                    twentyfifteen_the_custom_logo();

                    if ( is_front_page() && is_home() ) : ?>
                        <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
                    <?php else : ?>
                        <p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></p>
                    <?php endif;

                    $description = get_bloginfo( 'description', 'display' );
                    if ( $description || is_customize_preview() ) : ?>
                        <p class="site-description"><?php echo $description; ?></p>
                    <?php endif;
                ?>
                <button class="secondary-toggle"><?php _e( 'Menu and widgets', 'twentyfifteen' ); ?></button>
            </div><!-- .site-branding -->
        </header><!-- .site-header -->

        <?php get_sidebar(); ?>
    </div><!-- .sidebar -->

    <div id="content" class="site-content">
上述代码来自于著名的Twenty_Fifteen主题中的header.php文件定义。

猜你喜欢

转载自blog.51cto.com/zhuxianzhong/2168734