ペチパーノート

WEB開発系Tipsブログです。

PHP defineとconstの違い

PHPには定数とオブジェクト定数があり、それぞれdefine関数とconstキーワードで宣言できる。
具体的にはこんな感じ。

<?php
// 定数
define('MESSAGE', 'Hello World');
echo MESSAGE;

// オブジェクト定数
class MyClass {
    const MESSAGE = 'Hello World';
}
echo MyClass::MESSAGE;

defineとconstの違いは、グローバルなのかクラスのものなのかという点と、
宣言時に演算が使えるかという違いがある。

<?php
define('MESSAGE'100);      // OK
define('MESSAGE1', 100 + 10); // OK
define('MESSAGE2', time());   // OK

<?php
class MyClass {
    const MESSAGE1 = 100;      // OK
    const MESSAGE3 = 100 + 10; // NG
    const MESSAGE2 = time();   // NG
}