値が変更できない定数をクラス内に定義することができます。 定数は、通常の変数とは異なり、定義または使用する際に
$
記号を付けません。
static
メンバーのように、 定数値はオブジェクトのインスタンスから (
$object::constant
を使用して) アクセスすることはできません。
定義する値は定数表現である必要があり、(例えば)変数・クラスのメンバー・ 演算結果あるいは関数のコールなどであってはいけません。
例 19-17. 定数の定義と使用
<?php
class
MyClass
{
const
constant
=
'constant value'
;
function
showConstant
() {
echo
self
::
constant
.
"\n"
;
}
}
echo
MyClass
::
constant
.
"\n"
;
$class
= new
MyClass
();
$class
->
showConstant
();
// echo $class::constant; is not allowed
?>
|
|