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

方法一:
直接寫在入口文件處
<?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框架中自定義一個(gè)全局函數(shù)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
分享名稱:怎么在YII2框架中自定義一個(gè)全局函數(shù)-創(chuàng)新互聯(lián)
文章轉(zhuǎn)載:http://www.chinadenli.net/article18/iijgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、微信公眾號(hào)、ChatGPT、App開發(fā)、網(wǎng)站導(dǎo)航、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容