当前位置: 移动技术网 > IT编程>开发语言>PHP > YII2框架自定义全局函数的实现方法小结

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

2020年05月11日  | 移动技术网IT编程  | 我要评论

家装电视背景墙,2009年12月思想汇报,安全黑板报

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

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

方法一:

直接写在入口文件处

<?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';
 
//自定义函数
function test() {
  echo 'test ...';
}
 
(new yii\web\application($config))->run();

方法二:

在app下创建common目录,并创建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';
 
//引入自定义函数
require __dir__ . '/../common/functions.php';
 
$config = require __dir__ . '/../config/web.php';
 
(new yii\web\application($config))->run();

方法三:

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

tools.php的代码如下:

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

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

<?php
namespace app\controllers;
 
use yii\web\controller;
use app\helpers\tools;
 
class indexcontroller extends controller
{
 
  public function actionindex()
  {
    tools::test();
  }
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网