2013-01-16 16 views
1

我正在使用Yii作为我的web应用程序。在此我一直常量类模型和扩展如何在yii中构造常量

CUserIdentity如..

class Constants extends CUserIdentity 
{ 
CONST ACCOUTN_ONE = 1; 
CONST ACCOUTN_TWO = 2; 
CONST ACCOUTN_THREE = 3; 
} 

在这里,我可以访问常量像Constants::ACCOUTN_ONE,它会返回正确的结果1

但是,当我开始构建常量动态表示..

$type = 'ONE'; 
$con = "Constants::ACCOUTN_".$type; 
echo $con; 

它将显示为常量:: ACCOUTN_ONE ;

我期待在这里1

请纠正我,如果任何错误..

回答

0
$type = 'ONE'; // You created string 

$con = "Constants::ACCOUTN_".$type; // Created other string 

echo $con; // Printed it 

您刚刚打印字符串,不评价它。
是的,它会显示为常量:: ACCOUTN_ONE;

您需要eval()(坏)来评价你的代码,或使用此方案:

echo Constant($con);

+0

对不起,我的坏..回声常量($ CON);对我来说工作正常.. – Abhi

+0

@abhi:多数民众赞成在没有办法做到这一点,eval是非常糟糕的,使用[$$](http://php.net/manual/en/language.variables.variable.php) – DarkMukke

+2

在这种情况下@DarkMukke $$不起作用。 –

1
$type = 'ONE'; 
$con = "Constants::ACCOUTN_".$type; 
echo Constant($con); 
-1

我这样做有 它的一类,而回:

/** 
* Lots of pixie dust and other magic stuff. 
* 
* Set a global: Globals::key($vlaue); @return void 
* Get a global: Globals::key(); @return mixed|null 
* Isset of a global: Globals::isset($key); @return bool 
* 
* Debug to print out all the global that are set so far: Globals::debug(); @return array 
* 
*/ 
class Globals 
{ 

    private static $_propertyArray = array(); 

    /** 
    * Pixie dust 
    * 
    * @param $method 
    * @param $args 
    * @return mixed|bool|null 
    * @throws MaxImmoException 
    */ 
    public static function __callStatic($method, $args) 
    { 
     if ($method == 'isset') { 
      return isset(self::$_propertyArray[$args[0]]); 
     } elseif ($method == 'debug') { 
      return self::$_propertyArray; 
     } 

     if (empty($args)) { 
      //getter 
      if (isset(self::$_propertyArray[$method])) { 
       return self::$_propertyArray[$method]; 
      } else { 
       return null; //dont wonna trow errors when faking isset() 
      } 
     } elseif (count($args) == 1) { 
      //setter 
      self::$_propertyArray[$method] = $args[0]; 
     } else { 
      throw new Exception("Too many arguments for property ({$method}).", 0); 
     } 

    } 
}