codecamp

PHP常量

PHP教程 - PHP常量

常量用于确保在运行脚本时值不会改变。

句法

要定义常量,请使用define()函数,并包括常量的名称,后面是常量的值,如下所示:

define( "MY_CONSTANT", "1" ); // MY_CONSTANT always has the string value "1"

注意

  • Constants may only contain scalar values such as Boolean, integer, float, and string (not values such as arrays and objects).
  • Constants can be used from anywhere in your PHP program without regard to variable scope.
  • Constants are case-sensitive.


实施例1


<?PHP
  define("aValue", 8); 
  print aValue; 
?>

上面的代码生成以下结果。

实施例2

将true作为第三个参数传递给define()使常量不区分大小写:


<?PHP
define("SecondsPerDay", 86400, true); 
print SecondsPerDay; 
print SECONDSperDAY; 
?>

上面的代码生成以下结果。



实施例3

defined()函数基本上是等价于 isset()的常量,因为它返回true,如果你传递给它的常量字符串已定义。

例如:


<?PHP
define("SecondsPerDay", 86400, true); 
if (defined("Secondsperday")) { 
    // etc 
} 
?>

实施例4

constant()返回常量的值。


<?PHP
define("SecondsPerDay", 86400, true); 
$somevar = "Secondsperday"; 
print constant($somevar); 
?>

上面的代码生成以下结果。

实施例5

使用数学常数计算圆面积


<?php //from  ww w.j  a v a  2s  .co  m
         $radius = 4; 

         $diameter = $radius * 2; 
         $circumference = M_PI * $diameter; 
         $area = M_PI * pow( $radius, 2 ); 

         echo "A radius of " . $radius . " \n "; 
         echo "A diameter of " . $diameter . " \n "; 
         echo "A circumference of " . $circumference . " \n "; 
         echo "An area of " . $area . " \n "; 
               
?>  

上面的代码生成以下结果。

PHP数字转换
PHP数据类型转换
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Operator

Introduction

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }