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

Mat*_*kle 1 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();
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 7

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

define ('FOO', "test foo"); 
define ('BAR', "test bar"); 
Run Code Online (Sandbox Code Playgroud)

然后,要访问它们,请不要将它们的名称放在引号中:

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/>"; 
  } 
} 
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因你想获得常量的值而你只拥有它在变量中的名字,你可以使用以下constant函数:

define ('FOO', "test foo"); 

$name = 'FOO';
$value = constant($name);

// You would get the same effect with
// $value = FOO;
Run Code Online (Sandbox Code Playgroud)

在这种特殊情况下,看起来类常量可能更合适:

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/>"; 
  } 
} 
Run Code Online (Sandbox Code Playgroud)