php自訂常量與類常量區別分析

來源:互聯網
上載者:User
1. 自訂常量

常量的值只能是標量資料(boolean,integer,float 和 string)或 null。

常量一旦被定義,就不能被重新定義或者取消定義。

有兩種定義方式:

  • define()函數來定義常量

define('STATUS', 3); // 如果第三個參數設定為true,則大小寫不敏感

echo STATUS;

  • const關鍵字來定義常量

const NAME = 4;

echo NAME;

還可以用函數 constant() 來擷取常量的值。

使用defined()函數,檢查某個名稱的常量是否存在。


2. 類常量

可以在類中定義常量,常量的值必須是一個定值,不能是變數,類屬性或其它操作(如函數調用)的結果。但在PHP5.6中,對常量進行了增強,允許常量計算,允許使用包含數字、字串字面值和常量的運算式結果來定義const常量。常量的值也可以為一個數組,但不能是變數。

定義類常量只能使用const關鍵字。

class MyClass {    const AB = 2;    public function showConstant(){        echo self::AB;    }}echo MyClass::AB;$obj = new MyClass();$obj -> showConstant();MyClass::showConstant();$className = 'MyClass';echo $className::AB;

執行個體:

/** * 1、define(name,value,case_insensitive) 自訂全域常量, 預設大小寫敏感 * 2、const 定義類常量。 * 3、常量名前不要使用”$” * 4、常量的命名一般全部使用大寫字母。 *///定義全域常量 LANGUAGEdefine('LANGUAGE','中國');echo language;//languageecho LANGUAGE;//中國//定義全域常量 CNdefine('CN','中國',TRUE);echo CN;//中國echo cn;//中國//定義類常量class ConstTest{const VERSION = '1.0';function ConstTest(){//類內部使用“self::常量名”調用,不能使用$thisecho 'self::VERSION='.self::VERSION;}}//執行個體化 ConstTest,目的是調用建構函式new ConstTest();//外部調用類常量,通過“類名::常量名”直接調用,無需執行個體化。echo 'VERSION='.(ConstTest::VERSION);echo '<br>';//array get_defined_constants ([ bool $categorize = false ] ) 返回所有已定義的常量//print_r(get_defined_constants(true));//bool defined ( string $name ) 檢查該名稱的常量是否已定義。echo defined('cn')?'true':'false';

列印結果:

language中國中國中國self::VERSION=1.0VERSION=1.0true

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.