PHP5.6 CONST新特性幾個例子

來源:互聯網
上載者:User


PHP5.6起CONST新特性定義類常量可以使用常量標量運算式(Constant scalar expressions),例如:


<?php
 
class MyTimer {
    const SEC_PER_DAY = 60 * 60 * 24;
}
 
?>

define和CONST的區別是define可以用於定義全域常量,而CONST是定義類的常量。


static靜態變數與define,CONST的區別是static定義的變數是可以改變的,而後兩者不行,並且static靜態變數是隨類直接在記憶體中初始化,可以直接用,如$oneclass::hobby.

define可以定義數組嗎?例如define(‘A_ARRAY’,array(‘o’=>’ooo’,’x’=>’xxx’)).

在PHP5.6之前是不行的,但是可以通過serialize把數組序列化,如:


# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));
 
# use it
$my_fruits = unserialize (FRUITS);

PHP5.6之後可以直接const定義一個數組:

const DEFAULT_ROLES = array('guy', 'development team');

或者:

const DEFAULT_ROLES = ['guy', 'development team'];

如果是PHP7,可以直接用define定義數組:


define('DEFAULT_ROLES', array('guy', 'development team'));

聯繫我們

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