search
HomeBackend DevelopmentPHP TutorialDetailed introduction to the usage of PHP constants and variables_PHP tutorial

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
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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools