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

定数は、次のように、スクリプトの先頭で 1 回だけ定義する必要があります。

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

しかし、あるクラスのメソッドで定数を定義するのは良い考えではないと思います。もちろん、ほとんどの場合、それらの値を変数で取得する必要はありません。

于 2011-12-15T18:54:02.723 に答える