search
HomeBackend DevelopmentPHP Tutorial作为一名PHPER,您如何命名临时变量

如题,在编写代码的时候,总会遇到一些临时变量
那么你通常会选择给临时变量取个什么名字,
比如

$foo, $a, $x

等等?

回复内容:

如题,在编写代码的时候,总会遇到一些临时变量
那么你通常会选择给临时变量取个什么名字,
比如

$foo, $a, $x

等等?

临时变量名,主要就是看用在哪里的
如果是用在循环中的肯定是

$i, $j, $k

如果是用foreach中的话,多数情况会是

$k, $v, $key, $val

如果是用临时使用的

$temp, $t

真不知道是干什么用,还要用的话,一般我叫

$ignore_me

另外就是根据类型叫名称

$int, $num, $str, $arr

简单易读有意义的单词

临时变量跟普通变量一样命名,变量的生命周期不从变量名体现。

<code>    一个变量既然存在,就一定是不能删的。他必然有类型,他必然有用途,既然有类型有用途,他必须有自己的名字,哪怕是 $intNumber、$keyOfUsersArray、$tempFileUploaded 也比 $tmp1、$tempFile 好。

    最糟糕的两个变量名是 $data1 和 $data2,我认为再次就是 $tmp 、 $temp 了。


    如果你们公司只有一个临时工,那么你可以叫他 "临时工" ,这没问题。但是如果新来了一个临时工呢?叫 "新来的临时工" ?再来怎么办?所以最好的办法是一开始就给他们取个名字。比如 "胖王","李花匠","小寸头","王大力"...
</code>

补充一种,《重构——改善既有代码的设计》中介绍的一种去除临时变量的方法——使用查询代替临时变量(Replace Temp With Query):

重构前:

...
$basePrice = $this->quantity * $this->itemPrice; //临时变量$basePrice

if ($basePrice > 1000) {
    return $basePrice * 0.95;
} else {
    return $basePrice * 0.38;
}
...

重构后:

...
if ($this->basePrice() > 1000) {
    return $this->basePrice() * 0.95;
} else {
    return $this->basePrice() * 0.38;
}

...
//用于代替临时变量的查询式
public function basePrice() {
    return $this->quantity * $this->itemPrice;
}
...

书中所述的使用动机:
临时变量的问题在于:它们是暂时的,而且只能在所属函数内使用.由于临时变量只有在所属函数内才可见,所以它们会驱使你写出更长的函数,因为只有这样你才能访问到想要访问的临时变量.如果把临时变量替换为一个查询式(query method),那么同一个class中的所有函数都将可以获得这份信息.这将带给你极大帮助,使你能够为这个class编写更清晰的代码.

循环里的和@lazyboy的差不多,其他的就是变量名加_tmp后缀

不明白为什么非要有“临时”的概念,脚本运行完所有变量全销毁,运行的时候,我们很少会主动unset它,讨论他的生命周期又有什么意义呢。

至于作用域内的,这个随心情呗。

$temp
$tmp

就我来说,如果是单独一个临时变量我会用_完事,多个就要带点含义了,不过总是要以_开头。呵呵。

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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.