1. 程式人生 > >Yii2.0中Yii::$app與Yii 1.0中Yii:app()的理解

Yii2.0中Yii::$app與Yii 1.0中Yii:app()的理解

框架源碼 靜態 UNC 一個 eap eba 你在 this 模式

一直不明白Yii::$app與Yii::app(),查找yii框架源碼後如下記錄分享

(1)在Yii1.0中Yii::app()返回的是你在index.php裏創建的CWebApplication實例,在對應的CWebApplication,入口文件:

Yii::createWebApplication($configFile)->run();

對應的類中查找:

public static function createWebApplication($config=null)
{
return self::createApplication(‘CWebApplication‘,$config);

}

追到下一個類中的靜態函數:

public static function createApplication($class,$config=null)
{
return new $class($config);
}

查到構造函數:

public function __construct($config=null)
{
//將創建的webapp實例賦值給Yii的靜態屬性$app,在整個進程中可以使用Yii::app()來使用這個應用對象,這是一個單例模式
Yii::setApplication($this);
}

(2)在Yii2.0中最常用的服務定位器是application(應用)對象,可以通過 \Yii::$app 訪問,調用Application的構造方法,而其繼承自yii\base\Application構造方法為:

public function __construct($config = [])
{
Yii::$app = $this;
$this->setInstance($this);
$this->state = self::STATE_BEGIN;
$this->preInit($config);
$this->registerErrorHandler($config);
Component::__construct($config);
}

Yii::$app作為一個應用對象實例操控應用全局!

Yii2.0中Yii::$app與Yii 1.0中Yii:app()的理解