PHP 替代控制结构,有什么缺点吗? [英] PHP Alternative Control Structures, any drawbacks?

查看:29
本文介绍了PHP 替代控制结构,有什么缺点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 PHP 代码,这些代码无需任何模板即可生成 HTML,而且按照他们的结构方式很难阅读.我注意到的一种大幅改进流程的方法是在某些情况下使用 : endif 而不是 { } 块以提高可读性.(参见 http://php.net/manual/en/control-structures.alternative-syntax.php)

  • 这是便携式的吗?
  • 这是标准吗?
  • 这是否会以任何显着的方式变慢(我知道它需要更多字符)

干杯!

解决方案

这是便携的吗?

是的

<块引用>

这是标准吗?

是的

<块引用>

这是否会以任何显着的方式变慢(我知道它需要更多字符)

我不知道.

但是恕我直言,如果您将其与 HTML 结合使用,它会极大地提高可读性和可维护性.

示例:

<div><?php if($value == "foo"): ?><p><?php echo $value;?></p><?php endif;?>

<?php endforeach;?>

对比

<div><?php if($value == "foo") { ?><p><?php echo $value;?></p><?php } ?>

<?php } ?>

这只是一个小例子,但我认为 endifendforeach 更容易识别为 <?php } ?>.所以是的,一定要在 HTML 中使用它!

我不会在其他任何地方使用它,因为在普通"代码中我发现它更难阅读.

I've been working with PHP code that generates HTML without any templating, and it's quite spaghetti and difficult to read with the way they've structured it. One way to drastically improve following the flow I've noticed is to use : endif instead of { } blocks in some cases to increase readability. (See http://php.net/manual/en/control-structures.alternative-syntax.php)

  • Is this portable?
  • Is this standard?
  • Is this slower in any significant way (I understand it takes more chars)

Cheers!

解决方案

Is this portable?

Yes

Is this standard?

Yes

Is this slower in any significant way (I understand it takes more chars)

I don't know.

But imho it increases readability and maintainability very much if you use it in combination with HTML.

Example:

<?php foreach($array as $value): ?>
    <div>
    <?php if($value == "foo"): ?>
        <p><?php echo $value; ?></p>
    <?php endif; ?>
    </div>
<?php endforeach; ?>

vs

<?php foreach($array as $value) { ?>
    <div>
    <?php if($value == "foo") { ?>
        <p><?php echo $value; ?></p>
    <?php } ?>
    </div>
<?php } ?>

It is just a small example but I think endif and endforeach are much easier to spot as <?php } ?>. So yes, definitely use it with HTML!

I don't use it anywhere else though because in "normal" code I find it more difficult to read.

这篇关于PHP 替代控制结构,有什么缺点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆