PHP - what are constants
What are constants? A constant can be understood as a quantity whose value does not change (such as pi); or after the constant value is defined, it cannot be changed anywhere else in the script. Constants in PHP are divided into custom constants and system constants.
The syntax of define() function is:
bool define(string $constant_name, mixed $value[, $case_sensitive = true])
It has 3 parameters (aka ingredients):
The first parameter "constant_name" is a required parameter, the name of the constant, that is, the identifier, the naming rules of the constant are the same as those of the variable, but pay attention, it does not need the dollar sign. The second parameter "value" is a required parameter, which is the value of the constant. The third parameter "case_sensitive" is an optional parameter, specifying whether it is case-sensitive or not. If it is set to true, it means insensitive. Generally, if the third parameter is not specified, the default value of the third parameter is false.
<?php $p = "PII"; //constant names are usually uppercase define("PI",3.14); //define function defines constants, 3 parameters (constant name, constant value, case sensitive (default false sensitive)) define($p,3.14); echo PI; echo "<br />"; echo PII; echo "<br />"; ?>
PHP - the role of constants
What is the use of constants?
常量主要功效是可以避免重复定义,篡改变量值。在我们进行团队开发时,或者代码量很大的时候,对于一些第一次定义后不改变的量,如果我们使用变量,在不知情的情况下,使用同一变量名时,变量值就会被替换掉,从而会引发服务器执行错误的任务。
<?php define("PIL",3.14); $r=3; echo "面积为:".(PIL*$r*$r)."<br />"; echo "周长为:".(2*PIL*$r)."<br />"; ?>
PHP-认识一下系统常量
系统常量是PHP已经定义好的常量,我们可以直接拿来使用,常见的系统常量有:
(1)__FILE__ :php程序文件名。它可以帮助我们获取当前文件在服务器的物理位置。
(2)__LINE__ :PHP程序文件行数。它可以告诉我们,当前代码在第几行。
(3)PHP_VERSION:当前解析器的版本号。它可以告诉我们当前PHP解析器的版本号,我们可以提前知道我们的PHP代码是否可被该PHP解析器解析。
(4)PHP_OS:执行当前PHP版本的操作系统名称。它可以告诉我们服务器所用的操作系统名称,我们可以根据该操作系统优化我们的代码。
<?php //系统常量 echo __FILE__; //PHP程序文件名 echo "<br />"; echo __LINE__; //PHP文件行数 echo "<br />"; echo PHP_VERSION; //PHP解析器版本号 echo "<br />"; echo PHP_OS;//系统名 echo "<br />"; ?>
PHP-常量如何取值
定义了常量,那么就要使用常量,那么如何获取常量值呢?
获取常量值的有两种方法取值。第一种是使用常量名直接获取值;例如计算圆周率的面积,如下:
<?php
define("PI",3.14);
$r=1;
$area = PI*$r*$r; //计算圆的面积
?>
第二种是使用constant()函数。它和直接使用常量名输出的效果是一样的,但函数可以动态的输出不同的常量,在使用上要灵活、方便,其语法格式如下:
mixed constant(string constant_name)
<?php $p=""; //定义圆周率的两种取值 define("PI1",3.14); define("PI2",3.142); //定义值的精度 $height = "中"; //根据精度返回常量名,将常量变成了一个可变的常量 if($height == "中"){ $p = "PI1"; }else if($height == "低"){ $p = "PI2"; } $r=1; $area = constant($p)*$r*$r; //constant()函数获取常量值 echo $area; ?>
PHP-如何判定常量是否被定义
如果常量被重复定义以后,PHP解析器会发出“Constant XXX already defined”的警告,提醒我们该常量已经被定义过。那么,在团队开发,或代码量很大的情况下,我们如何去判定一个常量是否被定义呢?
defined()函数可以帮助我们判断一个常量是否已经定义,其语法格式为:
bool defined(string constants_name)
它只有参数constant_name,指的是要获取常量的名称,若存在则返回布尔类型true,否则返回布尔类型false; (注:bool表示函数返回值类型为布尔类型)
<?php //判断常量是否被定义 defined()函数 define("PI1",3.14); $p = "PI1"; $is1 = defined($p);//存在返回true $is2 = defined('PI2');//不存在返回false var_dump($is1); var_dump($is2); ?>