1

我将 Yii 用于我的 Web 应用程序。在此我将常量类保留在模型中并扩展

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

如有错误请指正。。

4

3 回答 3

1
$type = 'ONE';
$con = "Constants::ACCOUTN_".$type;
echo Constant($con);
于 2013-01-16T13:24:23.203 回答
0
$type = 'ONE'; // You created string

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

echo $con; // Printed it

您只是打印了字符串而不对其进行评估。
是的,当然它会显示为 Constants::ACCOUTN_ONE;

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

echo Constant($con);

于 2013-01-16T13:21:57.357 回答
-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);
        }

    }
}
于 2013-01-16T13:51:57.387 回答