Heim  >  Artikel  >  Backend-Entwicklung  >  玩转php常量_PHP教程

玩转php常量_PHP教程

WBOY
WBOYOriginal
2016-07-14 10:08:121175Durchsuche

常量的命名规则

命名: 与变量相同的命名规则
方法:define()函数
格式:define('常量名','具体值');
例子:define('PI',3.14);
 
常量与变量的比较
相同:
1:命名规则相同(但一般为大写)
不同:
1:引用常量时不用$,直接用名称.
2:常量只能用define定义,不能用赋值语句
3:常量一旦定义就不能重新定义或取消定义
4:常量的值只能是标量(只能是整型、浮点型、布尔型、字符型、NULL)
[php]  
  
//定义常量  
  
define('pi',3.14);  
  
//计算园的面的面积  
$r=3;  
  
echo pi*$r*$r;  
//结果:28.26  
  
  
//常量定义过后,不能再重新定义  
define('pi',3.23);  
  
//结果:Notice: Constant pi already defined in C:\wamp\www\0124\05.php on line 15  
  
//常量不能重新赋值  
pi=100;  
echo pi;  
  
//结果:Parse error: syntax error, unexpected '=' in C:\wamp\www\0124\05.php on line 21  
//会有语法上的错误  
  
$PI=10;  
  
function text(){  
     
echo $PI;//函数有作用域。此$PI变量是函数里面的与外边的$PI不是一个。  
   echo pi;//常量一次定义,可以再任何地方使用  
}  
  
//结果:Notice: Undefined variable: PI in C:\wamp\www\0124\05.php on line 31  
  
text();  
?>  
如何判断一个常量有没有定义?
define 定义常量
defined 判断常量
[php] 
  
if(defined('PI')){  
  
   echo 'PI常量已经定义了。
';  
}else{  
     echo 'PI常量未定义,我来定义它
';  
     define('PI',33322);  
}  
echo PI;  
  
?>  
[php]  
结果:PI常量未定义,我来定义它  
     33322  
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/477800.htmlTechArticle常量的命名规则 命名: 与变量相同的命名规则 方法:define()函数 格式:define(常量名,具体值); 例子:define(PI,3.14); 常量与变量的比较 相同: 1:命名...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn