简体   繁体   English

如何定义应用程序中随处可用的全局常量?

[英]How to define a global constant available everywhere in the application?

How can I define an UPLOAD_DIR constant (or equivalent) so that I can use it everywhere? 如何定义UPLOAD_DIR常量(或等效)以便我可以在任何地方使用它?

I tried this as an application configuration parameter 我尝试将其作为应用程序配置参数

'params'=>array(
            'upload_dir'=>Yii::app()->baseUrl . '/images/uploads/',
),

but Yii::app()->baseUrl cannott be used inside the config file. 但是Yii::app()->baseUrl baseUrl cannott可以在配置文件中使用。

You can do this inside index.php , after the call to Yii::createApplication and before Yii::app()->run() : 你可以在调用Yii::createApplicationYii::app()->run()之前在index.php执行此操作:

define ('UPLOAD_DIR', Yii::app()->baseUrl . '/images/uploads/');

You would then use it just like any other PHP constant, eg echo UPLOAD_DIR . 然后,您将像任何其他PHP常量一样使用它,例如echo UPLOAD_DIR

Edit: When I said after createApplication and before run , I meant exactly that (also, not that there is both a createWebApplication and a createApplication , which is a more generalized version of the former). 编辑:当我在createApplication之后和run之前说过时,我createApplication意味着(同样,并不是说存在createWebApplicationcreateApplication ,它是前者的更通用版本)。

So if you currently have 所以,如果你现在有

Yii::createWebApplication(...)->run();

you have to split it into 你必须把它拆分成

Yii::createWebApplication(...);
define ('UPLOAD_DIR', Yii::app()->baseUrl . '/images/uploads/');
Yii::app()->run();

Another option would be to just add another property to your application class. 另一种选择是将另一个属性添加到您的应用程序类。 For example, if you have a class MyApplication inside your protected/components directory then you can simply do this: 例如,如果您在protected/components目录中有一个class MyApplication那么您可以这样做:

class MyApplication extends CWebApplication {
    // ...other code...
    public function getUploadDir() {
        return $this->baseUrl.'/images/uploads/';
    }
}

You would then access this as Yii::app()->uploadDir . 然后,您将以Yii::app()->uploadDir

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM