Home  >  Article  >  Backend Development  >  How to set constants in php

How to set constants in php

青灯夜游
青灯夜游Original
2021-09-14 18:31:024119browse

How to set constants in php: 1. Use the define() function, the syntax "define('constant name', 'constant value')"; 2. Use the const keyword, the syntax "const constant name = constant value;".

How to set constants in php

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

The so-called constant is a quantity that cannot be changed, in PHP Once a constant 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.

How to set constants

1. Use the define() function

Legal constants A name can only begin with a letter and an underscore, and can be followed by any length of letters, numbers, or underscores. In PHP, you can define a constant through the define() function. The syntax of the define() function is as follows:

define(string $name, mixed $value [, bool $case_insensitive = false])

define() The description of the function parameters is as shown in the following table:

Parameters Description
$name Required parameter, constant name (needs to be wrapped in double quotes or single quotes)
$value Required parameter, constant value
$case_insensitive Optional parameter, Specify whether to be case-sensitive. The default is case-sensitive. If set to true, it means case-insensitive

2. Use the const keyword

In addition to using the define() function, you can also use the const keyword to define constants. The syntax of the const keyword is as follows:

const 常量名 = 常量值;

The following uses examples to demonstrate the use of constants:

<?php
header("Content-type:text/html;charset=utf-8");
define(&#39;WebSite&#39;, &#39;php中文网&#39;);
const url = &#39;https://www.php.cn/&#39;;
echo WebSite.&#39;<br>&#39;;
echo url;
?>

Running results:

How to set constants in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to set 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