2013-01-16 15 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); 
     } 

    } 
}