本文實(shí)例講述了YII2框架自定義全局函數(shù)的方法。分享給大家供大家參考,具體如下:
有些時(shí)候我們需要自定義一些全局函數(shù)來完成我們的工作。
方法一:
直接寫在入口文件處
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?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引入。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?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的代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
<?php //注意這里,要跟你的目錄名一致 namespace app\helpers; class Tools { public static function test() { echo 'test ...' ; } } |
然后我們在控制器里就可以通過命名空間來調(diào)用了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php namespace app\controllers; use yii\web\Controller; use app\helpers\tools; class IndexController extends Controller { public function actionIndex() { Tools::test(); } } |
希望本文所述對大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。
原文鏈接:https://www.cnblogs.com/jkko123/p/8655544.html