Php入門教程之PHP常量使用方法詳解

來源:互聯網
上載者:User

PHP 常量
define() 函數用於定義常量。一個常量一旦被定義,就不能再改變或者取消定義。

定義常量的例子:

 代碼如下 複製代碼

<?php
define("CONSTANT", "你好!");
echo CONSTANT;
?>

常量名和其它任何 PHP 標籤遵循同樣的命名規則。合法的常量名以字母或底線開始,後面跟著任何字母,數字或底線。

常量預設為大小寫敏感,按照慣例常量標識符總是大寫的,在指令碼執行期間該值不能改變。

定義常量和定義變數的區別:

1.常量前面沒有貨幣符號($)
2.常量只能用 define() 函數定義,而不能通過指派陳述式
3.常量可以不用理會變數範圍的規則而在任何地方定義和訪問
4.常量一旦定義就不能被重新定義或者取消定義
5.常量的值只能是標量
PHP內建了大量預定義常量,具體的可以在網上搜PHP手冊裡面有具體的內容。


判斷一個常量是否已經定義


如何判斷一個php常量是否已經定義過了,突然之間還有點迷茫,暈,特意查了下手冊,備案本次總結結果如下:

(1)判斷常量是否存在

 代碼如下 複製代碼

 if(defined('MYCONSTANT')){ 

    echo MYCONSTANT;  

 }

(2)判斷變數是否定義

 代碼如下 複製代碼

if(isset($myvar)){ 

    echo "存在變數$myvar.";  
3 }


(3)判斷函數是否存在

 代碼如下 複製代碼

if(function_exists('imap_open')){
 echo "存在函數imag_open";
}else{
 echo "函數imag_open不存在";
}


常量和變數相比,不同點:

1:常量是全域有效, 因此在頁面內,函數內,類內部甚至數組內部都可以直接引用.
 

 代碼如下 複製代碼
   $a=66;
    function t(){ echo $a; }
    t();//此時不能列印出來99,因為函數範圍影響,如果要列印出99,可以改為:
    define(“A”,66);
    function t(){ echo A; }
    t();

2:常量一旦定義,就不可以重新定義,不可以清除.也不可以修改;

常量也可以動態哦

 

 代碼如下 複製代碼

define("A","常量介紹");
  define("B","常量動態調用");
  $c=$_get['c'];//此處直接把b的值,並不會再b的值當成常量名再次解析
  echo constant($c);// constant(常量名)  ---> 返回常量的值


 

物件導向之const常量修飾符

中常用的常量修飾符const。

我們知道,在PHP中定義常量是通過define()函數來完成的,但在類中定義常量不能使用define(),而需要使用const修飾符。類中的常量使用const定義後,其訪問方式和靜態成員類似,都是通過類名或在成員方法中使用self訪問,但在PHP 5.3.0之後也可以使用對象來訪問。被const定義的常量不能重新賦值,如果在程式中試圖改變它的值將會出現錯誤

 代碼如下 複製代碼


<?php 

    class MyClass { 

          const CONSTANT = 'CONSTANT value' ; //使用const聲明一個常量,並直接賦上初使值 

            function showConstant() {                

                   echo  self ::CONSTANT ."<br>" ;//使用self訪問常量,注意常量前不要加“$” 

             } 

      } 
      echo MyClass:: CONSTANT . "<br>" ; //在類外部使用類名稱訪問常量,也不要加”$” 
      $class = new MyClass();                      

     $class->showConstant();                       

      echo $class ::CONSTANT;  // PHP 5.3.0之後 

 ?>

關注細節:使用const定義的常量名稱前不需要使用“$“符號,且常量名稱通常都是大寫的。


試圖為const定義的常量賦值,將會出現錯誤。

 代碼如下 複製代碼

<?php 

     class MyClass { 

          const CONSTANT = 'CONSTANT value' ;   

             function setCONSTANT(){ 

               self ::CONSTANT  = 'news CONSTANT' ;//程式運行結果將會出錯。 

      } 

                                                                                                                                                                                         

      } 
     echo MyClass:: CONSTANT ;           

                                                                                                                                                                            

?>


CONSTANTS and PHP Class Definitions

Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, or string (no array or other object types) -- right away.

不能在類裡面使用"define('MY_VAR', 'default value')"來定義常量,你必須使用PHP的關鍵字 'const'去初始化一個標量--boolean, int, float, or string (除了數組和其他物件類型)、

 代碼如下 複製代碼

<?php

define('MIN_VALUE', '0.0');   // RIGHT - Works OUTSIDE of a class definition.
define('MAX_VALUE', '1.0');   // RIGHT - Works OUTSIDE of a class definition.

//const MIN_VALUE = 0.0;         WRONG - Works INSIDE of a class definition.
//const MAX_VALUE = 1.0;         WRONG - Works INSIDE of a class definition.

class Constants
{
  //define('MIN_VALUE', '0.0');  WRONG - Works OUTSIDE of a class definition.
  //define('MAX_VALUE', '1.0');  WRONG - Works OUTSIDE of a class definition.

  const MIN_VALUE = 0.0;      // RIGHT - Works INSIDE of a class definition.
  const MAX_VALUE = 1.0;      // RIGHT - Works INSIDE of a class definition.

  public static function getMinValue()
  {
    return self::MIN_VALUE;
  }

  public static function getMaxValue()
  {
    return self::MAX_VALUE;
  }
}

?>

#Example 1:
You can access these constants DIRECTLY like so:
 * type the class name exactly.
 * type two (2) colons.
 * type the const name exactly.

#Example 2:
Because our class definition provides two (2) static functions, you can also access them like so:
 * type the class name exactly.
 * type two (2) colons.
 * type the function name exactly (with the parentheses).

 代碼如下 複製代碼

<?php

#Example 1:
$min = Constants::MIN_VALUE;
$max = Constants::MAX_VALUE;

#Example 2:
$min = Constants::getMinValue();
$max = Constants::getMaxValue();

?>

 

Once class constants are declared AND initialized, they cannot be set to different values -- that is why there are no setMinValue() and setMaxValue() functions in the class definition -- which means they are READ-ONLY and STATIC (shared by all instances of the class).

當類常量被聲明和初始化後,他們就不能被設定成其他值--這就是為什麼他們在類定義時沒有setMinValue()和setMaxValue()這兩個方法--這說明他們都是唯讀而且是靜態(被所有該類的對象共用)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.