使用大括号在PHP中构建代码 [英] Use curly brackets to structure code in PHP

查看:88
本文介绍了使用大括号在PHP中构建代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将PHP中的代码片段括在方括号内(而不使用片段作为函数)?

Is it possible to enclose code fragments in PHP within brackets (without using the fragment as a function)?

以下代码的行为方式与没有大括号时的行为方式相同吗?还是可能会出现问题,这取决于括号内或括号外使用的是哪种代码?

Would the following code behave the same way as it would without the curly brackets? Or might there be any problems depending on what kind of code used inside or outside the brackets?

例如,将:

<?php

// First Code-Block
{# several lines of code
}

// Second Code-Block
{# another several lines of code
}

?>

总是具有与此相同的方式:

Always behave the same way as this:

<?php

// First Code-Block
# several lines of code

// Second Code-Block
# another several lines of code

?>

推荐答案

如果用大括号括起来,PHP代码的行为不会改变.但是,您不能在大括号内使用一些PHP语句:

PHP code behavior does not change if you enclose it within curly brackets. However, you can't use some PHP statements inside curly brackets:

  • namespace声明;
  • 命名空间use声明以别名或导入任何名称;
  • 全局const声明;
  • __halt_compiler().
  • namespace declarations;
  • namespace use declarations to alias or import any names;
  • global const declarations;
  • __halt_compiler().

这意味着,以下脚本将起作用:

This means, the following script will work:

<?php
const x = 5;
echo x;

但以下内容无法编译:

<?php
{
  const x = 5;
  echo x;
}

这篇关于使用大括号在PHP中构建代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆