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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

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.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles