Namespace Confusion In Yii2

I’m confused why in Yii 2 we can access the global Yii class from inside a namespace without a “\”.

The PHP manual clearly states:

So for unqualified class names (Names without any "\") it should not fall back to global context, if you are inside a namespace.

Now i wonder, why this works:


namespace app\controllers;

use yii\web\Controller;

class SiteController extends Controller


    public function actionTest()


        echo Yii::t('test','test');


There’s no &#092; in front of Yii:t(). So according to the above quote this should be resolved to app\controllers\Yii::t() and throw an error. But it doesn’t!

I’ve created the same scenario with 2 simple files:



    // No namespace - so we define a global class

    class foo {

        public static function x() {

            echo "x";





    namespace bar;

    include "foo.php";


    // Unqualified class name is resolved to bar\foo::x() and gives an error


Here i do get an error. So what am i missing from Yii2?

It’s probably because there’s

namespace yii\base;

use Yii;

scattered across the framework?

It doesn’t work for me.

Oh, you’re right. I looked at the wrong action in my code. But then all the Yii::$app->… will also not work in the demo application.

So the rule is: You can write Yii::$app in non-namespaced code, like e.g. view files. Everywhere else it must be \Yii::$app. But maybe we should not differ at all and use \Yii::$app everywhere? Alternatively the namespaces could remove from the app code again.