Getting a call to the undefined method Yii :: app () in a layout view

I recently started using Yii 2 , and I am having problems with the layout file to get the following error:

 Call to undefined method Yii::app() 

This is my layout file:

 <?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $content string */ ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang="<?=Yii::$app->language?>"> <head> <title><?=Html::encode($this->title)?></title> <meta charset="<?=Yii::$app->charset?>"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <?=Html::csrfMetaTags()?> <link href="<?=Yii::app()->request->baseUrl;?>/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link href="<?=Yii::app()->request->baseUrl;?>/css/custom.css" rel="stylesheet" media="screen"> <script type="text/javascript" src="<?=Yii::app()->request->baseUrl;?>/js/bootstrap.min.js"></script> <script type="text/javascript" src="<?=Yii::app()->request->baseUrl;?>/js/scripts.js"></script> <!--[if lte IE 8]> <script src="<?=Yii::app()->request->baseUrl;?>/js/html5shiv.min.js"></script> <script src="<?=Yii::app()->request->baseUrl;?>/js/respond.min.js"></script> <![endif]--> <?php $this->head() ?> </head> <body> <?php $this->beginBody() ?> <?=$content?> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?> 

When I use Yii::$app , I get no problems, but if I use Yii::app() , I get this error.

I started using Yii::app() in some places when I read, and I was told that you should use the following to include absolute path names in the views:

 Yii::app()->request->baseUrl 

... and enable jQuery usage:

 Yii::app()->clientScript->registerCoreScript("jquery"); 

However, when I do something with app() , I get the above error.

I tried replacing app() with $app ; the page was loaded fine, but in Yii::$app->request->baseUrl there was an empty value.

What am I doing wrong here?

+7
php yii yii2
source share
3 answers

In Yii 2, $app is a property of Yii, not a method, so you should use Yii::$app->blah .

A source

+11
source share

Try the following: Yii::$app->request->baseUrl;

Yii::$app is a static var for the Yii2 application class, 'yii \ web \ Application'. It refers to an instance of the Yii Application class. Since the Request class is configured as the default application component, you have access to many useful properties: Requesting a class description

Yii2 also comes with a bunch of helper classes that do many of the same things: BaseUrl Helper

Usage: Url::base(); ... be sure to use the namespace by placing use yii\helpers\Url; at the top of your controller (below the main namespace).

+1
source share
 Yii::$app->homeUrl 

Yii::$app is a static variable for the Yii2 application class, 'yii \ web \ Application'. This applies to an instance of the Yii Application class. Since the request class is configured as an application component, by default you have access to all the useful properties.

-one
source share

All Articles