Home  >  Article  >  Backend Development  >  What is the difference between variables and constants in php

What is the difference between variables and constants in php

青灯夜游
青灯夜游Original
2021-11-03 19:17:324746browse

Difference: 1. Constants can only be defined using the define() function or the const keyword; while variables without defined keywords or functions are defined when assigning values. 2. Use "$" to modify the variable name, but not the constant name. 3. Variable values ​​can be changed, but constant values ​​cannot. 4. Variables have global and local scopes, while constants have only global scope.

What is the difference between variables and constants in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

What are php constants ?

The so-called constant is a quantity that cannot be changed. Once a constant in PHP is defined, it cannot be modified or undefined.

PHP constants are usually used to store data that does not change and is not expected to change. The data can only be data of four scalar data types: integer, floating point, string, and Boolean. However, Starting from PHP7, constants support array types.

The difference between constants and variables in php

Different definition methods:

There are no variables in php The defined keyword or function is defined when assigned. PHP constants can only be defined using the define() function or the const keyword.

Different names:

php variable names need to be modified with a dollar sign ($), but php constant names do not need to be modified. There is no dollar sign ($) in front of the constants. It is recommended that PHP variable names be lowercase. When they consist of multiple words, the first letter of the first word should be lowercase, and the first letter of the remaining words should be uppercase. It is recommended that PHP constant names be in all uppercase letters.

The values ​​have different meanings:

The values ​​stored in PHP variables can be changed, while the values ​​stored in PHP constants cannot be changed.

No need for scope:

php variables have global scope and local scope. PHP constants are generally defined outside all functions, and the scope of constants is global.

The data type range is different:

php variables can be of any data type, while php constants can only be scalar types (integer, float/double, string, boolean) .

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What is the difference between variables and constants in php. For more information, please follow other related articles on the PHP Chinese website!

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