如何在yii中构造常量

时间:2013-01-16 13:19:37

标签: php constants

我正在使用Yii作为我的网络应用程序。在这里,我在模型中保留了Constants类并扩展了

来自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;

它将显示为Constants :: ACCOUTN_ONE;

我期待1

如果有任何错误,请纠正我。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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

echo $con; // Printed it

你只是打印字符串而不评估它 是的,它会显示为Constants :: ACCOUTN_ONE;

您需要使用eval()(错误)评估您的代码,或使用此方案:

echo Constant($con);

答案 2 :(得分:-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);
        }

    }
}