search
HomeBackend DevelopmentPHP TutorialPHP变量标识符的一些守则

PHP变量标识符的一些规则

PHP变量标识符提供了非常特别的方便。但是,相当多的从事多年的PHP程序员却无法清楚它的具体用法,从而出错时,不知哪里错了。所以,现在总结一下。便于大家快速掌握。
PHP变量的运行机制是,将变量标识符$后的字符串,或表达式运算结果的字符串作为变量名,去变量池获取变量值。
可见,PHP相当于提供了一个变量的“名称指针”。它不同于C++的地址指针,因为,不会有空地址的不安全性。也不会有变量内存溢出的问题。所有这些PHP都给我们完成了。
变量标识符:
$:以后面的字符串为变量名,取同名变量。
?? $a='Hello';
?? $$a = 'world';
{}将其中的表达式解析成字串,并取此字串的变量,{}不能单独在表达式外部存在,否则就会当成流程控制而报错。这就是说, {}前必有$,或者外面必有引号。
echo $a, ${$a}; echo $a, $$a;

二者的区别: $总是寻找后面的第一个字串, {}是将内部的表达式解析为字串。PHP正是用这一方式实现了变量的“名称指针”。

${}:由{}返回字串交给$再处理。用途:对于表达式结果取变量。
?如:${$array[$i][$j]} , 如果使用 $$array[$i][$j]} 则PHP会找 $$array这个变量。而不是找$array[$i][$j]为结果的变量名的变量。

{}在函数中与表达式中
猜猜看:下面程序返回什么:

   $a='Hello';   $$a = 'world';   echo '1 ', $a, '{$a}', '</br>';   echo '2 ', $a, "{$a}", '</br>';   echo '3 ', $a, "{{$a}}", '</br>';      echo '4 ', $a, "${$a}", '</br>';      echo '5 ', $a, ${$a}, '</br>';    echo '6 ', $a, "{${$a}}", '</br>';    echo '7 ', $a, "{{${$a}}}", '</br>';    echo '8 ', $a, "$$a", '</br>';         echo '9 ', $a, "{a}", '</br>';        echo '10 ', $a, "${a}", '</br>';

?

结果:

?? echo '1 ', $a, '{$a}', '';
输出是:1 Hello{$a}?

//正常情况下,单引号是非执行字串,按原结果返回。但是:Smarty同样会将其进行解析!!所以, Smarty模板中, ‘{$a}’这样的表达式,仍可能出现的是你不想要的结果!!
假如:str_replace('{$foo} ',$foo, '{$foo}.some');
因为上面的原因:需要改为:
? str_replace(array('{', '$foo',} '),array('',$foo, ''), '{$foo}.some');

?? echo '2 ', $a, "{$a}", '';
输出是: 2 HelloHello
双引号中,无论是否有{},变量总会被解析。
?? echo '3 ', $a, "{{$a}}", '';??
输出是: 3 Hello{Hello}?
//所以,如果要输出带{}的结果,则需要加两层。
?? echo '4 ', $a, "${$a}", '';?
输出是: 4 Helloworld
?? echo '5 ', $a, ${$a}, '';
输出是: 4 Helloworld
// ${$表达式},无论外面是否带双引号,结果都是一样的?

?? echo '6 ', $a, "{${$a}}", '';?
输出是: 6 Helloworld
?? echo '7 ', $a, "{{${$a}}}", '';
输出是: 7 Hello{world}
//要输出带{}的结果,必须多加一层。
echo '8 ', $a, "$$a", '';
输出是: 8 Hello$Hello
//双引号中的$只执行一次。所以,结果就不是你所要的。

附注:{}还可用于数组,即对数组下标访问。即
$array[$i][$j] 与 $array{$i}{$j}是等价的。但正常,由于PHP文档中给出是的[]。而字符串是字节数组,所以,我们只有在用字节数组模式访问字符串时,才使用{}
$a='ux:Cache'; $a{2}=''; echo $a; 这个结果是什么,你知道吗?
echo '9 ', $a, "{a}", '';
输出是:9 Hello{a}
?? echo '10 ', $a, "${a}", '';
输出是:10 HelloHello可以见到, {}外有$, {}也会将结果送给$解析。

总结:
双引号中的$只会解析一次。不会进行多重解析。echo “$$a”,则要改为 echo “${$a}”;
{}遇$成为{$foo}就会被解析。要输出带{}的结果,则要{{$foo}}
$是向后寻找字符串,所以,数组或表达式的结果: 不能
$$array[$i][$j] 而是要 ${$array[$i][$j]}

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools