PHP常量

2018-02-22 16:40 更新

PHP教程 - PHP常量

常量用于確保在運行腳本時值不會改變。

句法

要定義常量,請使用define()函數(shù),并包括常量的名稱,后面是常量的值,如下所示:

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; 
?>

上面的代碼生成以下結(jié)果。

實施例2

將true作為第三個參數(shù)傳遞給define()使常量不區(qū)分大小寫:


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

上面的代碼生成以下結(jié)果。



實施例3

defined()函數(shù)基本上是等價于 isset()的常量,因為它返回true,如果你傳遞給它的常量字符串已定義。

例如:


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

實施例4

constant()返回常量的值。


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

上面的代碼生成以下結(jié)果。

實施例5

使用數(shù)學(xué)常數(shù)計算圓面積


<?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 "; 
               
?>  

上面的代碼生成以下結(jié)果。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號