YII2框架自定義全局函數(shù)的實現(xiàn)方法小結(jié)
本文實例講述了YII2框架自定義全局函數(shù)的方法。分享給大家供大家參考,具體如下:
有些時候我們需要自定義一些全局函數(shù)來完成我們的工作。
方法一:
直接寫在入口文件處
<?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引入。
<?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的代碼如下:
<?php
//注意這里,要跟你的目錄名一致
namespace app\helpers;
class Tools
{
public static function test()
{
echo 'test ...';
}
}
然后我們在控制器里就可以通過命名空間來調(diào)用了。
<?php
namespace app\controllers;
use yii\web\Controller;
use app\helpers\tools;
class IndexController extends Controller
{
public function actionIndex()
{
Tools::test();
}
}
更多關(guān)于Yii相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結(jié)》、《php優(yōu)秀開發(fā)框架總結(jié)》、《smarty模板入門基礎(chǔ)教程》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP stream_context_create()函數(shù)的使用示例
這篇文章主要介紹了PHP stream_context_create()函數(shù)的使用示例,stream_context_create()函數(shù)是用來 創(chuàng)建打開文件的上下文件選項,用于fopen(),file_get_contents()等過程的超時設(shè)置、代理服務(wù)器、請求方式、頭信息設(shè)置的特殊過程,需要的朋友可以參考下2015-05-05
app判斷鏈接參數(shù)后綴跳轉(zhuǎn)不同地址的方法
下面小編就為大家?guī)硪黄猘pp判斷鏈接參數(shù)后綴跳轉(zhuǎn)不同地址的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
Zend Framework動作助手FlashMessenger用法詳解
這篇文章主要介紹了Zend Framework動作助手FlashMessenger用法,分析了動作助手FlashMessenger的功能,并結(jié)合實例形式演示了FlashMessenger的使用技巧,需要的朋友可以參考下2016-03-03

