Home > Backend Development > PHP Problem > How to set constants in php

How to set constants in php

青灯夜游
Release: 2023-03-12 14:42:02
Original
4241 people have browsed it

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])
Copy after login

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

ParametersDescription
$nameRequired parameter, constant name (needs to be wrapped in double quotes or single quotes)
$valueRequired parameter, constant value
$case_insensitiveOptional 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 常量名 = 常量值;
Copy after login

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;
?>
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template