这篇文章将为大家详细讲解有关怎么在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();
}
}
关于怎么在YII2框架中自定义一个全局函数就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。