Home Backend Development PHP Tutorial Detailed introduction to the usage of PHP constants and variables_PHP tutorial

Detailed introduction to the usage of PHP constants and variables_PHP tutorial

Jul 13, 2016 pm 05:13 PM
php introduce variable constant usage detailed

In the past, I rarely introduced the usage and reference table of variables, constants and magic constants in PHP in such detail. This article is of great help to beginners and friends who need to know more can refer to it.

Variables:

Variables are used to store values, such as numbers, text strings, or arrays.

Once a variable is set, we can use it repeatedly in the script.

All variables in PHP start with the $ symbol.

The correct way to set variables in PHP is:

 代码如下 复制代码
$var_name = value;

Beginners to PHP often forget the $ sign in front of variables. If you do that, the variable will be invalid.

Let’s try to create a variable that holds a string, and a variable that holds a numeric value:

 代码如下 复制代码
$txt = "Hello World!";
$number = 16;
?>

1. How to define variables, and how is it different from languages ​​such as C#?
Variables in PHP are represented by a dollar sign followed by the variable name. Variable names are case-sensitive. For example:

The code is as follows Copy code
代码如下 复制代码
$var='Jim';
$VAR='Kimi;
echo "$var,$VAR";//输出“Jim,Kimi"
$var='Jim';

$VAR='Kimi;
echo "$var,$VAR";//Output "Jim,Kimi"

?>You may also care about the naming of variables, which is actually the same as in most languages. 2. Are variables case-sensitive?

 代码如下 复制代码
1 2 $foo = 'Bob'; // 赋值'Bob'给foo
3 $bar = &$foo; // 通过$bar引用.注意&符号
4 $bar = "My name is $bar"; // 修改 $bar
5 echo $bar;
6 echo $foo; // $foo 也修改了.
7 ?>
As mentioned in 1, it is case sensitive.

Note, one thing that needs to be explained is that since PHP4, the concept of reference assignment has been introduced, which is actually similar to references in most languages, but I think the most similar one is C/C++ because it also uses the "&" symbol. For example:

The code is as follows Copy code
1 2 $foo = 'Bob'; // Assign 'Bob' to foo
3 $bar = &$foo; // Referenced through $bar. Note the & symbol

4 $bar = "My name is $bar"; // Modify $bar

5 echo $bar;

6 echo $foo; // $foo has also been modified.
代码如下 复制代码
$a = "b";
$$a = "123";
echo $b;
?>
7 ?>
Like other languages, only variables with variable names can be referenced. Okay, now everyone should have a general understanding of variables. Now let's look at indirect references and string concatenation of variables. ①Indirect reference of variables: Let’s look at an example first
The code is as follows Copy code
$a = "b";<🎜> $$a = "123";<🎜> echo $b;<🎜> ?>

The above output is 123

We can see that there is an extra $ in the second line of code, and the variable is accessed through the specified name. The specified name is stored in $a("b"), and the value of this variable $b is changed to 123. Therefore, such a variable of $b is created and assigned.

You can increase the number of references arbitrarily by adding an additional $ mark in front of the variable.

②String connection: Let’s look at an example first

 代码如下 复制代码
$a = "PHP 4" ;
$b = "功能强大" ;
echo $a.$b;
?>

It should be noted that in PHP 4.2.0 and subsequent versions, the default value of the PHP instruction register_globals is off. This is a major change to PHP. Setting register_globals to off affects the global availability of the predefined set of variables. For example, to get the value of DOCUMENT_ROOT, you would have to use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT. Another example, use $_GET['id'] instead of $id from the URL http://www.example.com/test Get the id value in .php?id=3, or use $_ENV['HOME'] instead of $HOME to get the value of the environment variable HOME

We see the third line of code, the English (period) sign, which can concatenate strings into a merged new string.

超全局变量 描述
$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 数组(依然有效,但反对使用)

Constant:

A constant is an identifier (name) of a simple value. As the name implies, the value cannot change during script execution (except for so-called magic constants, which are not constants). Constants are case-sensitive by default. Normally constant identifiers are always uppercase.

Constant names follow the same naming rules as any other PHP tag. Legal constant names begin with a letter or an underscore, followed by any letters, numbers, or underscores. The regular expression is expressed as follows: [a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*

① is data that cannot be changed during program execution. The scope of constants is global.

②The naming of constants is similar to variables, but without the dollar sign "$". A valid constant name begins with a letter or an underscore, followed by any number of letters, numbers, or underscores.

③ Generally, constants in PHP are in uppercase letters and are divided into system constants and custom constants.

We have just briefly talked about system constants, which will be introduced later.

1. __FILE__ Default constant refers to the PHP program file name and path;
2. __LINE__ Default constant refers to the number of lines of the PHP program;
3. __CLASS__ The name of the class;

Custom constant: define a constant through the define() function,

The syntax format is: bool define ( string $name, mixed $value [, bool case_$insensitive] )

name: Specify the name of the constant.
value: Specifies the value of the constant.
insensitive: Specifies whether the constant name is case-sensitive. If set to true, it is case-insensitive; if set to false, it is case-sensitive. If this parameter is not set, the default value is false.

// Legal constant name
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");

//Illegal constant name
define("2FOO", "something");

// The following definition is legal, but should be avoided: (custom constants do not start with __)
// Maybe one day in the future PHP will define a __FOO__ magic constant
// This will conflict with your code
define("__FOO__", "something");

?>

几个 PHP 的“魔术常量”
名称 说明
__LINE__ 文件中的当前行号。
__FILE__ 文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对路径(如果是符号连接,则是解析后的绝对路径),而在此之前的版本有时会包含一个相对路径。
__DIR__ 文件所在的目录。如果用在被包括文件中,则返回被包括的文件所在的目录。它等价于 dirname(__FILE__)。除非是根目录,否则目录中名不包括末尾的斜杠。(PHP 5.3.0中新增) =
__FUNCTION__ 函数名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该函数被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。
__CLASS__ 类的名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该类被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。
__METHOD__ 类的方法名(PHP 5.0.0 新加)。返回该方法被定义时的名字(区分大小写)。
__NAMESPACE__ 当前命名空间的名称(大小写敏感)。这个常量是在编译时定义的(PHP 5.3.0 新增)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629213.htmlTechArticleIn the past, I rarely introduced the usage and reference table of variables, constants and magic constants in PHP in such detail. This article is of great help to beginners and friends who need to know more can...
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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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 do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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 are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles