常量只应在脚本顶部定义一次,如下所示:
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/>";
}
}