Home Backend Development PHP Tutorial php中大括号作用介绍_php技巧

php中大括号作用介绍_php技巧

May 17, 2016 am 09:12 AM
php big parantheses

一、不管什么程序,function name(){}, for(){}, ….太多了,不说也知道做什么用了。
二、$str{4}在字符串的变量的后面跟上{}刚大括号和中括号一样都是把某个字符串变量当成数组处理。
三、{$val}这时候大括号起的作用就是,告诉PHP,括起来的要当成变量处理。

复制代码 代码如下:

$arr=array(0=>123, 'name'=>'你好');
foreach($array as $k=>$v){
echo "select * from blog_blogs where blog_tags like '%{$arr[$k]}%' order by blog_id"; //加一个大括号只是将作为变量的标志符
}
echo '






';
foreach($array as $k=>$v){
echo "select * from blog_blogs where blog_tags like '%{{$arr[$k]}}%' order by blog_id"; //加两个大括号,外层的将作为普通的字符
}
//用大括号来区分变量
//echo "$arr['name']"; //用此句会报语法错误
echo "{$arr['name']}"; //此句正常,大括号内的字符将作为变量来处理
//$str{4} 在字符串的变量的后面跟上{} 大括号和中括号一样都是把某个字符串变量当成数组处理
$str = 'abcdefg';
echo $str{4};


{}大括号在php中的作用(PHP变量放在大括号里面的含义)

如:$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 变量后面加上一个大括号{},里面填上数字,就是指 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 )

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

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

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

一、使用大括号的变量
前一篇日志提到了,PHP Notice警告的是下面一句:

switch (${action}.'_'.${child}) {
初看并没有什么问题。我也查询了PHP手册上关于变量的定义:这里。
1、可变变量的情况
可见,与大部分资料一样,变量使用大括号的情况,在于“可变变量”(Variable variables)。其中提到:


引用
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
也就是说,为了在数组环境中也可以使用可变变量,因此,需要根据不同的情况,恰当的使用大括号{}限制变量的范围。${$a[1]} 与${$a}[1] 是完全不同的:


引用
${$a[1]} 这里$a[1]是一个变量;
${$a}[1] 这里$a是一个变量;
2、定界、避免歧义
实际上,这情况与可变变量时类似。例如,若使用“.”连接符,连接一个字符串,可能是这样:

echo $str.'_2010';
用大括号来写,可能更简单:

echo "${str}_2010";
可见,如果没有大括号,则可能把$str_2010整个作为一个变量来处理。当然,这样的写法,只能用在双引号中,单引号里面是不会执行变量替换的。

3、字符串变量中的单个字符
例如:
复制代码 代码如下:

$str='000';
$str{0}='1';
echo $str; //输出为100
?>

这不难理解,与中括号[]的作用是一致的,有点类似Python中把字符串看成对象的情况。所以,下面的语句功能相同:
复制代码 代码如下:

$str='000';
$str[0]='1';
echo $str; //也是输出100
?>

不过,这些都不是我想说明的内容,真正想描述的情况,请见下面。

二、变量使用大括号的异同
首先,把PHP的错误信息输出全部打开,即/etc/php.ini 为:


引用
error_reporting = E_ALL
display_errors = On
然后,打开测试页面,其中代码为:
复制代码 代码如下:

$test='123';
echo $test;
echo "${test}";
echo "{$test}";
echo ${test}.'_';
echo ${test};
?>

你会看到如下的结果:


引用
123123123
Notice: Use of undefined constant test - assumed 'test' in /var/www/html/phpcrm/testpages/variables.php on line 6
123_
Notice: Use of undefined constant test - assumed 'test' in /var/www/html/phpcrm/testpages/variables.php on line 7
123
这说明什么?
1、可接受的写法
从输出结果中“123123123”,表明前面三行的echo语句都是正常的:
复制代码 代码如下:

echo $test;
echo "${test}";
echo "{$test}";

2、不建议的写法
后面的两行都有Notice警告,也就是曾把test变量看成常量,只是后来才假设为变量来处理的。因此,为了避免歧义和冲突,不建议这样写:
复制代码 代码如下:

echo ${test}.'_';
echo ${test};

不过,可以有一种变通的写法
复制代码 代码如下:

echo ${'test'}.'_';
echo ${'test'};

这样写的话就不会报错了
3、不正确的写法
网上不少资料介绍,${var}与{$var}的作用是一样的。但是,如果你再加入一句:

echo {$test};
那么,你将会得到以下错误信息:


引用
Parse error: syntax error, unexpected '{' in /var/www/html/phpcrm/testpages/variables.php on line 8
这可不是Notice警告,是错误,因解析问题,程序将不能正常运行。

三、总结
结合前面两部分的内容,我相信,对于变量引用时使用大括号,应遵循以下原则:


引用
1、正确的写法为:${var} 的形式;
2、与双引号一同使用;
3、根据需表达的意思进行定界。
所以,最后我把switch一行改为:

switch ("${action}_${child}") {
即不再出现Notice警告。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles