PHP 大括号{} 的使用

                                                                                       PHP 大括号{} 的使用

1、将多个独立语句合并为一个复合语句。例如类class{},方法function{},if...else,for,foreach等。

2、在变量间接引用中进行定界,避免歧义。例如 ${$a[1]}与${$a}[1]的区分。

3、用于获取字符串变量中的单个字符(下标从0开始)

  例如:

$str = 'hello';
echo $str{1};	// 输出为 e ,也可 $str[1]
echo $str[2];	// 输出为 l ,也可 $str{2}

注意:

如果要检查某个字符串是否满足多少长度,可以考虑用这种大括号{} 加 isset 的方式替代 strlen 函数,
因为 isset 是语言结构,strlen 是函数,所以使用 isset 比使用 strlen 效率更高。

比如判断一个字符串的长度是否小于 5:
if ( !isset ( $str{5} ) ) 就比 if ( strlen ( $str ) < 5 ) 好。

4、界定变量的名称(php中输出变量加大括号{}作用)
代码比较:

$str = "hello";
$next_str1 = $str." world";	// hello world
$next_str2 = "{$str} world";	// hello world
$next_str3 = "$str world";	// hello world
$next_str4 = "{$str}world";	// helloworld
$next_str5 = "$str{world}";	// hello{world}
$next_str6 = "$strworld";       // Notice: Undefined variable: strworld in D:\...\trunk\app\controllers\Test.php on line 13
	

总结:

1. 表示{}里面的是一个变量  ,执行时按照变量来处理;
2. 在字符串中引用变量使用的特殊包括方式,这样就可以不使用.运算符,从而减少代码的输入量了;
3. 防止变量名和后面的字符串连在一起。

猜你喜欢

转载自blog.csdn.net/qq_36025814/article/details/83660004
今日推荐