提问人:Matthew Sprankle 提问时间:12/16/2011 更新时间:12/16/2011 访问量:5716
从变量变量调用定义的常量
Call defined constant from variable variable
问:
我试图在一个单独的函数中引用一个定义的常量。 我得到的错误是指未定义的变量以及定义为每个 FOO 和 BAR 的常量的变量。
class Boo {
public function runScare() {
$this->nowScaring('FOO');
$this->nowScaring('BAR');
}
private function nowScaring($personRequest) {
define ('FOO', "test foo");
define ('BAR', "test bar");
$person = ${$personRequest};
echo "<br/>Query selected is: " . $person . "<br/>";
}
}
$scare = new Boo;
$scare->runScare();
答:
0赞
Naftali
12/16/2011
#1
您只能定义一次常量,并且它们会全局定义。
9赞
Jon
12/16/2011
#2
常量应该只定义一次,在脚本的顶部,如下所示:
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/>";
}
}
如果出于某种原因,你想得到常量的值,而你所拥有的只是它在变量中的名称,你可以使用常量
函数来实现:
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/>";
}
}
0赞
Timur
12/16/2011
#3
class Boo {
public function runScare() {
$this->nowScaring('FOO');
$this->nowScaring('BAR');
}
private function nowScaring($personRequest) {
if( !defined('FOO') ){
define ('FOO', "test foo");
}
if( !defined('BAR') ){
define ('BAR', "test bar");
}
$person = constant($personRequest);
echo "<br/>Query selected is: " . $person . "<br/>";
}
}
$scare = new Boo;
$scare->runScare();
但我认为在某个类的方法中定义常量不是一个好主意。当然,在大多数情况下,您不需要按变量检索它们的值。
上一个:变量 + 字段中的对象
下一个:PHP:变量中的类属性链接
评论