Question

I am trying to refer to a defined constant in a separate function. The errors I am getting refer to the variable not defined and the variable defined as a constant for each FOO and 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();
Was it helpful?

Solution

Constants should be defined once only, at the top of your script, like this:

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

Then, to access them, don't put their names in quotes:

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

If for some reason you want to get the value of the constant and all you have is its name in a variable, you can do so with the constant function:

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

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

// You would get the same effect with
// $value = FOO;

In this particular case, it looks like that class constants might be a better fit:

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

OTHER TIPS

You can only define constants once and they get defined globally.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top