這篇文章將為大家詳細講解有關怎么在YII2框架中自定義一個全局函數,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
方法一:
直接寫在入口文件處
<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../config/web.php';
//自定義函數
function test() {
echo 'test ...';
}
(new yii\web\Application($config))->run();方法二:
在app下創建common目錄,并創建functions.php文件,并在入口文件中通過require引入。
<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
//引入自定義函數
require __DIR__ . '/../common/functions.php';
$config = require __DIR__ . '/../config/web.php';
(new yii\web\Application($config))->run();方法三:
通過YII的命名空間來完成我們自定義函數的引入,在app下創建helpers目錄,并創建tools.php(名字可以隨意)。
tools.php的代碼如下:
<?php
//注意這里,要跟你的目錄名一致
namespace app\helpers;
class Tools
{
public static function test()
{
echo 'test ...';
}
}然后我們在控制器里就可以通過命名空間來調用了。
<?php
namespace app\controllers;
use yii\web\Controller;
use app\helpers\tools;
class IndexController extends Controller
{
public function actionIndex()
{
Tools::test();
}
}關于怎么在YII2框架中自定義一個全局函數就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。