定数は、次のように、スクリプトの先頭で 1 回だけ定義する必要があります。
define ('FOO', "test foo");
define ('BAR', "test bar");
次に、それらにアクセスするには、名前を引用符で囲まないでください。
class Boo {
public function runScare() {
$this->nowScaring(FOO); // no quotes
$this->nowScaring(BAR); // no quotes
}
private function nowScaring($person) {
// And no need to "grab their values" -- this has already happened
echo "<br/>Query selected is: " . $person . "<br/>";
}
}
なんらかの理由で定数の値を取得したいが、変数にその名前しかない場合は、次のconstant
関数を使用してそれを行うことができます。
define ('FOO', "test foo");
$name = 'FOO';
$value = constant($name);
// You would get the same effect with
// $value = FOO;
この特定のケースでは、クラス定数の方が適しているように見えます。
class Boo {
const FOO = "test foo";
const BAR = "test bar";
public function runScare() {
$this->nowScaring(self::FOO); // change of syntax
$this->nowScaring(self::BAR); // no quotes
}
private function nowScaring($person) {
echo "<br/>Query selected is: " . $person . "<br/>";
}
}