本文實(shí)例講述了YII2框架自定義全局函數(shù)的方法。分享給大家供大家參考,具體如下:
有些時(shí)候我們需要自定義一些全局函數(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 ...';
}
}
然后我們?cè)诳刂破骼锞涂梢酝ㄟ^命名空間來調(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)于Yii相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結(jié)》、《php優(yōu)秀開發(fā)框架總結(jié)》、《smarty模板入門基礎(chǔ)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- YII2框架中使用RBAC對(duì)模塊,控制器,方法的權(quán)限控制及規(guī)則的使用示例
- YII框架模塊化處理操作示例
- YII分模塊加載路由的實(shí)現(xiàn)方法
- Yii中srbac權(quán)限擴(kuò)展模塊工作原理與用法分析
- YII模塊實(shí)現(xiàn)綁定二級(jí)域名的方法
- YII2框架中自定義用戶認(rèn)證模型,完成登陸和注冊(cè)操作示例
- YII框架實(shí)現(xiàn)自定義第三方擴(kuò)展操作示例
- Yii2框架自定義驗(yàn)證規(guī)則操作示例
- Yii2實(shí)現(xiàn)自定義獨(dú)立驗(yàn)證器的方法
- 深入淺析yii2-gii自定義模板的方法
- YII2框架中添加自定義模塊的方法實(shí)例分析