php如何定義常量、系統常量和使用常量

來源:互聯網
上載者:User
PHP中的常量分為自訂常量和系統常量,自訂常量需要使用PHP函數來進行定義,系統常量可以直接拿來使用,下面來看一下這兩種常量在使用上有什麼不同

1.自訂常量

* 必須用函數define()定義
* 定義完後其值不能再改變了
* 使用時直接用常量名,不能像變數一樣在前面加$s
例如:define("PI",3.14);定義一個常量
$area = PI*R*R; 計算圓的面積
define("URL","http://www.php.cn");
echo "我的網址是:".URL;

2 系統常量:

FILE :php程式檔案名稱
LINE :PHP程式檔案行數
PHP_VERSION:當前解析器的版本號碼
PHP_OS:執行當前PHP版本的作業系統名稱
可以直接拿來使用,例如要查看執行當前PHP版本的作業系統名稱,就可以寫成 echo PHP_OS

php定義和使用一個類常量

php類常量

我們可以在類中定義常量。常量的值將始終保持不變。在定義和使用常量的時候不需要使用$符號。

常量的值必須是一個定值,不能是變數,類屬性或其它操作(如函數調用)的結果。

Its also possible for interfaces to have constants. Look at the interface documentation for examples. 介面(interface)中也可以定義常量。請查看介面的文檔獲得更多樣本。

PHP5.3.0之後,我們可以用一個變數來動態調用類。但該變數的值不能為關鍵字self, parent 或static。

定義和使用一個類常量

<?phpclass MyClass{const constant = ‘constant value';function showConstant() {echo self::constant . “\n”;}}echo MyClass::constant . “\n”;$classname = “MyClass”;echo $classname::constant . “\n”; // PHP 5.3.0之後$class = new MyClass();$class->showConstant();echo $class::constant.”\n”; // PHP 5.3.0之後?>

Example #2 待用資料樣本

<?phpclass foo {// PHP 5.3.0之後const bar = <<<'EOT'barEOT;}?>

聯繫我們

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