您的位置:首页 > 编程语言 > PHP开发

php变量什么情况下加大括号{}

2010-06-28 16:04 246 查看
如:
$sql = "insert into article (`channel_id`,`title`,`detail`,`pub_time`) values ('{$cid}','{$title}','{$detail}','{$time}');";

不加似乎也可以,加{}是什么意思呢?
还有字段名 为什么要以``包括呢?

==================================================

最佳答案

至少便于阅读嘛~~~''是insert into语句要求的,因为字符串要成对出现嘛
加{}有时候是为了防止变量名和后面的字符串连在一起嘛
例如
{$cid}dd
如果cid=aa
那么{$cid}dd=aadd
不加的话你自己看看了$ciddd,岂不变成了ciddd变量了~~






















PHP变量放在大括号里面的含义

// The following is okay as it's inside a string. Constants are not
// looked for within strings so no E_NOTICE error here
print "Hello $arr[fruit]"; // Hello apple

// With one exception, braces surrounding arrays within strings
// allows constants to be looked for
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple

下面几个比较能说明原因的解释是:

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

其实输出那块是等同于print "hello ".$arr['fruit'];





















PHP: 字符串变量中大括号(花括号{})的作用

PHP 变量后面加上一个大括号{},里面填上数字,就是指 PHP 变量相应序号的字符。
例如:
$str = 'hello';
echo $str{0}; // 输出为 h
echo $str{1}; // 输出为 e
如果要检查某个字符串是否满足多少长度,可以考虑用这种大括号(花括号)加 isset 的方式替代 strlen 函数,因为 isset 是语言结构,strlen 是函数,所以使用 isset 比使用 strlen 效率更高。
比如判断一个字符串的长度是否小于 5:
if ( !isset ( $str{5} ) ) 就比 if ( strlen ( $str ) < 5 ) 好。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: