LoginSignup
1
0

More than 3 years have passed since last update.

PHPの定数について

Posted at

定数とは

宣言時に決めた値を再定義できない

PHPで定数を定義する方法2つ

define()で定数を定義する

define('定数名', '値');

 PHP7〜 配列定数を定義できるようになった。

// 定数をクラス外に定義
define('CONSTANT', ['key1' => 'hoge', 'key2' => 'fuga']);
class Sample
{
    function printConst()
    {
        // クラス内から定数にアクセスする場合
        print_r(CONSTANT);
    }
}
$sample = new Sample();
$sample->printConst();                 // CONSTANTが出力される
// クラス外から定数にアクセスする場合(同じ)
print_r(CONSTANT);                     // CONSTANTが出力される

constで定数を定義する

const '定数名' = '値';

 
PHP5.3 以上で使える。
PHP7〜 配列定数を定義できるようになった。
const はクラス定数を定義できる。

class Sample
{
    // 定数をクラス内に定義
    const CONSTANT = ['key1' => 'hoge', 'key2' => 'fuga'];
    function printConst()
    {
        // クラス内から定数にアクセスする場合
        print_r(self::CONSTANT);
    }
}
$sample = new Sample();
$sample->printConst();          // CONSTANTが出力される
// クラス外から定数にアクセスする場合
print_r(Sample::CONSTANT);      // CONSTANTが出力される

define()const の違い

  • define() は関数なので、const の方が高速に処理される。
  • define() は変数や関数の戻り値を使えて、const では使えない。
$func = function(){
    return '定数';
};
define('CONST_DEFINE', $func());
echo CONST_DEFINE;  // 定数が出力される
// 定数式に無効なものが含まれているという以下のエラーで終了する
// Fatal error: Constant expression contains invalid 
const CONST_CONST = $func();
echo CONST_CONST;   
  • define()if 文や function の中でも使える。
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0