当前位置:首页 > CMS教程 > 其它CMS > 列表

YII2框架自定义全局函数的实现方法小结

发布:smiling 来源: PHP粉丝网  添加日期:2022-02-19 09:45:25 浏览: 评论:0 

本文实例讲述了YII2框架自定义全局函数的方法,分享给大家供大家参考,具体如下:

有些时候我们需要自定义一些全局函数来完成我们的工作。

方法一:

直接写在入口文件处

  1. <?php 
  2. // comment out the following two lines when deployed to production 
  3. defined('YII_DEBUG'or define('YII_DEBUG', true); 
  4. defined('YII_ENV'or define('YII_ENV''dev'); 
  5.    
  6. require __DIR__ . '/../vendor/autoload.php'
  7. require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php'
  8.    
  9. $config = require __DIR__ . '/../config/web.php'
  10.    
  11. //自定义函数 
  12. function test() { 
  13.   echo 'test ...'
  14.    
  15. (new yii\web\Application($config))->run(); 

方法二:

在app下创建common目录,并创建functions.php文件,并在入口文件中通过require引入。

  1. <?php 
  2. // comment out the following two lines when deployed to production 
  3. defined('YII_DEBUG'or define('YII_DEBUG', true); 
  4. defined('YII_ENV'or define('YII_ENV''dev'); 
  5.    
  6. require __DIR__ . '/../vendor/autoload.php'
  7. require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php'
  8.    
  9. //引入自定义函数 
  10. require __DIR__ . '/../common/functions.php'
  11.    
  12. $config = require __DIR__ . '/../config/web.php'
  13.    
  14. (new yii\web\Application($config))->run(); 

方法三:

通过YII的命名空间来完成我们自定义函数的引入,在app下创建helpers目录,并创建tools.php(名字可以随意)。

tools.php的代码如下:

  1. <?php 
  2. //注意这里,要跟你的目录名一致 
  3. namespace app\helpers; 
  4.    
  5. class Tools 
  6.   public static function test() 
  7.   { 
  8.     echo 'test ...'
  9.   } 

然后我们在控制器里就可以通过命名空间来调用了。

  1. <?php 
  2. namespace app\controllers; 
  3.    
  4. use yii\web\Controller; 
  5. use app\helpers\tools; 
  6.    
  7. class IndexController extends Controller 
  8.    
  9.   public function actionIndex() 
  10.   { 
  11.     Tools::test(); 
  12.   } 
  13. }

Tags: YII2自定义全局函数

分享到: