php的常量定义:const VS define

As of PHP 5.3 there are two ways to define constants: Either using the const keyword or using the define() function:

const FOO = 'BAR'; 
define('FOO', 'BAR'); 

The fundamental difference between those two ways is that const defines constants at compile time, whereas define defines them at run time. What does that mean for you?

  • const cannot be used to conditionally define constants. It has to be used in the outermost scope:

    if (...) { 
        const FOO = 'BAR';    // invalid 
    } 
    // but 
    if (...) { 
        define('FOO', 'BAR'); // valid 
    } 
    

    Why would you want to do that anyways? One common application is to check whether the constant is already defined:

    if (!defined('FOO')) { 
        define('FOO', 'BAR'); 
    } 
    
  • const accepts a static scalar (number, string or other constant like true, false, null, __FILE__), whereas define() takes any expression:

    const BIT_5 = 1 << 5;    // invalid 
    define('BIT_5', 1 << 5); // valid 
    
  • const takes a plain constant name, whereas define() accepts any expression as name. This allows to do things like this:

    for ($i = 0; $i < 32; ++$i) { 
        define('BIT_' . $i, 1 << $i); 
    } 
    
  • consts are always case sensitive, whereas define() allows you to define case insensitive constants by passing true as the third argument:

    define('FOO', 'BAR', true); 
    echo FOO; // BAR 
    echo foo; // BAR 
    

So, that was the bad side of things. Now let's look at the reason why I personally always use const unless one of the above situations occurs:

  • const simply reads nicer. It's a language construct instead of a function and also is consistent with how you define constants in classes.
  • As consts are language constructs and defined at compile time they are a bit faster than define()s.

    It is well known that PHP define()s are slow when using a large number of constants. People have even invented things like apc_load_constants() and hidef to get around this.

    consts make the definition of constants approximately twice as fast (on development machines with XDebug turned on even more). Lookup time on the other hand does not change (as both constant types share the same lookup table): Demo.

Summary

Unless you need any type of conditional or expressional definition, use consts instead of define()s - simply for the sake of readability!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值