Brett Brett - 4 months ago 31
PHP Question

Getting Call to undefined method Yii::app() within layout view

I've recently started using

Yii 2
and I'm having some issues with the layout file with getting the below 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 issues, but if I use
Yii::app()
then I get that error.

I started using
Yii::app()
in some places as I was reading around and was told you should use the below to make sure to include absolute path names within views:

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


...and to include jQuery use:

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


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

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

What am I doing wrong here!?

Answer

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

Source

Comments