2011-12-15 142 views
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(); 

回答

7

常量应仅一次定义,在脚本的顶部,这样的:

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

然后,访问他们,不要把自己的名字放在引号:

​​

如果由于某种原因想要获得常数的值,并且您只需将其名称存储在变量中,则可以使用constant函数执行此操作:

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

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

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

在这种特殊情况下,它看起来像class constants可能是更好的选择:

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

只能定义常量一次,他们得到全局定义。

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

但我不`吨认为这是一个好主意,在某些类的方法来定义常量。当然,在大多数情况下,你不需要通过变量检索他们的值。