溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在YII2框架中自定義一個全局函數(shù)

發(fā)布時間:2021-03-17 15:33:57 來源:億速云 閱讀:144 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細講解有關(guān)怎么在YII2框架中自定義一個全局函數(shù),文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

方法一:

直接寫在入口文件處

<?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';
 
//自定義函數(shù)
function test() {
  echo 'test ...';
}
 
(new yii\web\Application($config))->run();

方法二:

在app下創(chuàng)建common目錄,并創(chuàng)建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';
 
//引入自定義函數(shù)
require __DIR__ . '/../common/functions.php';
 
$config = require __DIR__ . '/../config/web.php';
 
(new yii\web\Application($config))->run();

方法三:

通過YII的命名空間來完成我們自定義函數(shù)的引入,在app下創(chuàng)建helpers目錄,并創(chuàng)建tools.php(名字可以隨意)。

tools.php的代碼如下:

<?php
//注意這里,要跟你的目錄名一致
namespace app\helpers;
 
class Tools
{
  public static function test()
  {
    echo 'test ...';
  }
}

然后我們在控制器里就可以通過命名空間來調(diào)用了。

<?php
namespace app\controllers;
 
use yii\web\Controller;
use app\helpers\tools;
 
class IndexController extends Controller
{
 
  public function actionIndex()
  {
    Tools::test();
  }
}

關(guān)于怎么在YII2框架中自定義一個全局函數(shù)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI