How to write global functions in Yii2 and access them in any view (not the custom way)

Follow Step:
1) create following directory "backend/components"
2) create "BackendController.php" controller in "components" folder

<?php    
    namespace backend\components;
    use Yii;

    class BackendController extends \yii\web\Controller
    {
        public function init(){
            parent::init();

        }
        public function Hello(){
            return "Hello Yii2";
        }
    }

3) all backed controller extend to "BackendController" (like).

<?php
namespace backend\controllers;

use Yii;
use backend\components\BackendController;

class SiteController extends BackendController
{

    public function beforeAction($event)
    {
        return parent::beforeAction($event);
    }

    public function actionIndex(){
        /* You have to able for call hello function to any action and view */
        //$this->Hello(); exit;

        return $this->render('index');
    }
}

4) create your action view page "index.php" (like)

<?php
print $this->Hello();
?>

Controller functions are not accessible in the views.

In Yii1 the view attached to the controller whereas in Yii2 the view attaches to the View class (this was one of the core changes in Yii2). This separates the controller and view logic but also makes it harder for global functions, as you have noticed.

Yii2, itself, has also needed global functions. They have made "helpers", there are in fact a number of helpers: https://github.com/yiisoft/yii2/tree/master/framework/helpers each providing their own set of global functions for use.

If you haven't guessed yet, this is the best way to do globals in Yii2. It is also the standard compliant way as well (PSR-2 or whatever) and is considered better coding than normal globals.

So, you should actually be making your own custom helpers with your globals in, for example:

class MyHelpers
{
    public static function myGlobalToDoSomethingAwesome()
    {
        return $awesomeness;
    }
}

and just reference that in your view/controller like you would any helper:

use common\components\MyHelpers;
MyHelpers::myGlobalToDoSomethingAwesome();

One option is to create a file (probably in your components directory) that has your functions in it:

function myFunction($parameters)
{
    // Do stuff and return stuff
}

and then include it in your index.php file:

require_once(__DIR__ . "../components/MyGlobalFunctions.php');

The disadvantage is that this is now outside the OOP scope of the application. I used this method to create a dd() (dump and die) function like Laravel has.