Home  >  Article  >  Backend Development  >  How to define a custom constant in php

How to define a custom constant in php

silencement
silencementOriginal
2019-09-25 09:56:526236browse

How to define a custom constant in php

PHP default convention is that constant identifiers are always in uppercase letters, and the scope of constants is global and can be accessed anywhere in the script. Legal constant names start with a letter or an underscore, followed by

followed by any letters, numbers, or underscores. Letters are always capitalized. Once a constant is defined, it cannot be changed or undefined. Constants can only contain a single type of data, such as integers or

strings. When obtaining a constant value, you need to specify the name of the constant, but you do not need to add the $ sign. PHP system constants begin with __, and custom constants should try not to begin with __.

In PHP, use the define() function to define constants and assign values. The syntax format is:

boolean define(string name, mixed value [, bool case_insensitive])

Among them, name represents the name of the constant to be defined; value represents the value of the constant; case_insensitive represents Whether to be case-sensitive when referencing this constant. If this value is true, it means it is not case-sensitive.

In PHP5.3 and later versions, you can use the const keyword to define constants outside the class definition. Once a constant is defined, it cannot be changed or undefined.

If an undefined constant is used, PHP assumes that what it wants is the name of the constant itself, as shown in the figure when calling it with a string (HELLO corresponds to "HELLO"), and an E_NOTICE level will be issued. mistake. Example:

<?php
//合法的常量名
define("PI", "3.1415926");
define("MAXLENGTH", "100M");
define("TITLE", "PHP视频大全");
//PHP5.3之后新增的常量命名方式
const MIN_VALUE=0.0;
const MAX_VALUE=1.0;
?>

The above is the detailed content of How to define a custom constant 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