加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

YII2中如何自定义全局函数

发布时间:2020-12-14 13:37:42 所属栏目:大数据 来源:网络整理
导读:有些时候我们需要自定义一些全局函数来完成我们的工作。 方法一: 直接写在入口文件处 ?php// comment out the following two lines when deployed to productiondefined('YII_DEBUG') or define('YII_DEBUG',true);defined('YII_ENV') or define('YII_ENV',

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

方法一:

直接写在入口文件处

<?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 yiiwebApplication($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','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 yiiwebApplication($config))->run();

  

方法三:

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

tools.php的代码如下:

<?php
//注意这里,要跟你的目录名一致
namespace apphelpers;

class Tools
{
    public static function test()
    {
        echo 'test ...';
    }
}

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

<?php

namespace appcontrollers;

use yiiwebController;
use apphelperstools;

class IndexController extends Controller
{

    public function actionIndex()
    {
        Tools::test();
    }
}

  

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读