Search code examples
phpoopvariable-variables

Call defined constant from variable variable


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

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