duanchendu69495 2011-12-15 18:46
浏览 25
已采纳

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

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();
  • 写回答

3条回答 默认 最新

  • dongyue1988 2011-12-15 18:50
    关注

    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/>"; 
      } 
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计