Home Backend Development PHP Tutorial PHP 7: PHP 变量和常量的定义

PHP 7: PHP 变量和常量的定义

Jun 23, 2016 pm 02:29 PM

本章说说变量的定义。
如果对于变量和常量的定义,你会注意几个方面呢?你可能会想到:
如何定义变量,它和C# 等语言有什么不同呢? 变量区分大小写吗? PHP的变量还有其他重要的吗?
常量和变量的定义一样吗?  分别讲述吧。
1.如何定义变量,它和C# 等语言有什么不同呢?
   PHP 中的变量用一个 美元符号后面跟变量名来表示。变量名是 区分大小写的。例如:

  $var = ' Jim ' ;
   $VAR = ' Kimi;
  echo "$var,$VAR";//输出“Jim,Kimi"
 ?>

你可能还关心变量的命名,其实和大多数语言一样。
2. 变量区分大小写吗?
   如 1里说的,区分大小写。
  注意,需要说明的一点是自PHP4以来,引入了引用赋值的概念,其实和多数语言的引用类似,不过我觉得最类似的是C/C++.因为它也用到了"&"符号。例如: 

1  php
2  $foo   =   ' Bob ' ;               //  赋值'Bob'给foo
3  $bar   =   & $foo ;               //  通过$bar引用.注意&符号
4  $bar   =   " My name is $bar " ;   //  修改 $bar
5  echo   $bar ;
6  echo   $foo ;                 //  $foo 也修改了.
7  ?>  

和其他语言一样,只能对有变量名的变量才可以引用。
3. PHP其他重要点
预定义变量
预定义变量在PHP是一个重要的概念。 PHP 提供了大量的预定义变量。由于许多这些变量依赖于运行的服务器的版本和设置,及其它因素,所以并没有详细的说明文档。一些预定义变量在 PHP 以命令行形式运行时并不生效。

需要注意的是 在PHP 4.2.0 以及后续版本中,PHP 指令 register_globals 的默认值为 off。这是 PHP 的一个主要变化。让 register_globals 的值为 off 将影响到预定义变量集在全局范围内的有效性。例如,为了得到 DOCUMENT_ROOT 的值,将必须使用 $_SERVER['DOCUMENT_ROOT'] 代替 $DOCUMENT_ROOT,又如,使用 $_GET['id'] 来代替 $id 从 URL http://www.example.com/test.php?id=3 中获取 id 值,亦或使用 $_ENV['HOME'] 来代替 $HOME 获取环境变量 HOME 的值。

从 PHP 4.1.0 开始,PHP 提供了一套附加的预定数组,这些数组变量包含了来自 web 服务器(如果可用),运行环境,和用户输入的数据。这些数组非常特别,它们在全局范围内自动生效,例如,在任何范围内自动生效。因此通常被称为自动全局变量(autoglobals)或者超全局变量(superglobals)。(PHP 中没有用户自定义超全局变量的机制。)超全局变量罗列于下文中;而且,你也将注意到旧的预定义数组( $HTTP_*_VARS)仍旧存在。自 PHP 5.0.0 起,长格式的 PHP 预定义变量可以通过设置 register_long_arrays 来屏蔽。
下表是PHP的超全局变量:
超全局变量
描述
$GLOBALS 包含一个引用指向每个当前脚本的全局范围内有效的变量。该数组的键名为全局变量的名称。从 PHP 3 开始存在 $GLOBALS 数组。
$_SERVER 变量由 web 服务器设定或者直接与当前脚本的执行环境相关联。类似于旧数组 $HTTP_SERVER_VARS 数组(依然有效,但反对使用)。
$_GET 经由 URL 请求提交至脚本的变量。类似于旧数组 $HTTP_GET_VARS 数组(依然有效,但反对使用)。
$_POST 经由 HTTP POST 方法提交至脚本的变量。类似于旧数组 $HTTP_POST_VARS 数组(依然有效,但反对使用)。
$_COOKIE 经由 HTTP Cookies 方法提交至脚本的变量。类似于旧数组 $HTTP_COOKIE_VARS 数组(依然有效,但反对使用)。
$_FILES 经由 HTTP POST 文件上传而提交至脚本的变量。类似于旧数组 $HTTP_POST_FILES 数组(依然有效,但反对使用)
$_ENV 执行环境提交至脚本的变量。类似于旧数组 $HTTP_ENV_VARS 数组(依然有效,但反对使用)。
$_REQUEST  经由 GET,POST 和 COOKIE 机制提交至脚本的变量,因此该数组并不值得信任。所有包含在该数组中的变量的存在与否以及变量的顺序均按照 php.ini 中的 variables_order 配置指示来定义。此数组在 PHP 4.1.0 之前没有直接对应的版本。参见 import_request_variables()。
$_SESSION 当前注册给脚本会话的变量。类似于旧数组 $HTTP_SESSION_VARS 数组(依然有效,但反对使用)
变量的应用范围
 每个变量都有应用范围,那么PHP是怎么定义的呢?还是先看看下面代码吧:

 1  php
 2    $var = 0 ;
 3    function  test( $index )
 4   {
 5        $var = $var + 1 ;
 6        echo   " The  " . $index . "  number is  " . $var . "
" ;
 7   }
 8   test( 1 );
 9   test( 2 )
10  ?>

你认为以上的代码会显示什么结果呢?
如果你认为是下面:
结果1:

The  1   number  is  1
The  2   number  is 2

不好意思,你的结果是错误的。
其实正确的结果应该是:
结果2

The  1   number  is  1
The  2   number  is  1

那么你从其中发现了什么呢?我们可以知道虽然第2行的代码定义在外面,但第5行的变量和它是不一样的。第5行的变量仅在这个函数里使用。进一步的,如果我想调用第一行的变量而显示结果2.代码可以如下:

 1  php
 2    $var = 0 ;
 3    function  test( $index )
 4   {
 5        global   $var ;
 6        $var = $var + 1 ;
 7        echo   " The  " . $index . "  number is  " . $var . "
" ;
 8   }
 9   test( 1 );
10   test( 2 )
11  ?>

这个代码段和上面的代码段有何区别呢?注意第5行,多了一个 global关键字。明白了吧。
那么还有没有其他方法呢?答案是肯定的。
代码如下:

 1  php
 2    $var = 0 ;
 3    function  test( $index )
 4   {
 5       
 6        $GLOBALS [ " var " ] = $GLOBALS [ " var " ] + 1 ;
 7        echo   " The  " . $index . "  number is  " . $GLOBALS [ " var " ] . "
" ;
 8   }
 9   test( 1 );
10   test( 2 )
11  ?>

代码有什么特殊的吗?那就是用到了 $GLOBALS这个超全局变量。
PHP也有静态变量的说法。不过静态变量一般用在函数里,只能是局部变量了。看看下面代码吧:

 1  php
 2  function  Test()
 3  {
 4      static   $a   =   0 ;
 5      echo   $a . "
" ;
 6      $a ++ ;
 7  }
 8  Test();
 9  Test();
10  ?>  

结果为

1
2


PHP还有一个相当令人兴奋的特性: 可变变量
所谓可变变量,就是一个变量的变量名可以动态的设置和使用。
看看下面的例子:

1  php
2    $a = " hello " ;
3    $hello = " world " ;
4    echo   $a . "   " . $ $a ;
5  ?>  

输出的结果居然是hello,world.太神奇了。$$a其实就是$hello,因为$a的值是hello。
变量就这多了。下面看看常量。

常量
 PHP的常量是不是前面加const呢?让我们看一看。
不是的。在PHP必须用下面的方式定义。
bool define ( string name, mixed value [, bool case_insensitive] )
name 为常量名,value为常量的值。case_insensitive]为大小写敏感。默认为敏感。例如:

 1  php
 2  define ( " CONSTANT " ,   " Hello world. " );
 3  echo   CONSTANT ;  //  outputs "Hello world."
 4  echo   Constant ;  //  outputs "Constant" and issues a notice.
 5 
 6  define ( " GREETING " ,   " Hello you. " ,   true );
 7  echo  GREETING;  //  outputs "Hello you."
 8  echo  Greeting;  //  outputs "Hello you."
 9 
10  ?>  


常量和变量不同:

常量前面没有美元符号($);

常量只能用 define() 函数定义,而不能通过赋值语句;

常量可以不用理会变量范围的规则而在任何地方定义和访问;

常量一旦定义就不能被重新定义或者取消定义;

常量的值只能是标量。

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 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
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

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.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

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

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

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.

Explain Arrow Functions (short closures) introduced in PHP 7.4. Explain Arrow Functions (short closures) introduced in PHP 7.4. Apr 06, 2025 am 12:01 AM

The arrow function was introduced in PHP7.4 and is a simplified form of short closures. 1) They are defined using the => operator, omitting function and use keywords. 2) The arrow function automatically captures the current scope variable without the use keyword. 3) They are often used in callback functions and short calculations to improve code simplicity and readability.

See all articles