1. 程式人生 > 程式設計 >YII2框架自定義全域性函式的實現方法小結

YII2框架自定義全域性函式的實現方法小結

本文例項講述了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','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();
  }
}

更多關於Yii相關內容感興趣的讀者可檢視本站專題:《Yii框架入門及常用技巧總結》、《php優秀開發框架總結》、《smarty模板入門基礎教程》、《php面向物件程式設計入門教程》、《php字串(string)用法總結》、《php+mysql資料庫操作入門教程》及《php常見資料庫操作技巧彙總》

希望本文所述對大家基於Yii框架的PHP程式設計有所幫助。