从变量变量调用定义的常量

时间:2011-12-15 18:46:15

标签: php oop variable-variables

我试图在单独的函数中引用已定义的常量。 我得到的错误是指未定义的变量,以及为每个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();

3 个答案:

答案 0 :(得分:7)

常量应该只在脚本的顶部定义一次,如下所示:

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 constants可能更合适:

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/>"; 
  } 
} 

答案 1 :(得分:0)

您只能定义常量一次,并且全局定义它们。

答案 2 :(得分:0)

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();

但我不认为在某个类的方法中定义常量是个好主意。当然,在大多数情况下,您无需按变量检索它们的值。