1

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

3 回答 3

9

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

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/>"; 
  } 
} 
于 2011-12-15T18:50:35.550 回答
0

您只能定义一次常量,它们会被全局定义。

于 2011-12-15T18:47:38.470 回答
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();

But I don`t think it is a good idea to define constants in method of some class. And, of course, in most cases you have no need to retrieve theirs values by variable.

于 2011-12-15T18:54:02.723 回答