zl程序教程

您现在的位置是:首页 >  其他

当前栏目

ThinkPHP6.0 公共函数文件

文件 函数 公共 Thinkphp6.0
2023-06-13 09:17:03 时间

公共函数文件,可以理解为自定义函数文件

1. 公共函数文件位置


全局公共函数文件

app/common.php

应用公共函数文件

app/应用/common.php

2. 全局公共函数文件

自定义函数

app/common.php
<?php
// 应用公共文件

function getRand()
{
return mt_rand(100, 999);
}

在所有应用的控制器、模型中都可以直接使用该函数

<?php
namespace app\index\controller;

use app\BaseController;

class Index extends BaseController
{
public function index()
{
echo getRand() . ' ' . __METHOD__;
}
}

3. 应用公共函数文件位置


添加自定义函数

app/index/common.php
<?php

// index 应用公共函数文件

function getMd5Rand()
{
return md5(mt_rand(10, 99));
}

只能在index应用下使用该函数,在其他应用下使用则抛出未定义函数的错误

<?php
namespace app\index\controller;

use app\BaseController;

class Index extends BaseController
{
public function index()
{
echo getMd5Rand() . ' ' . __METHOD__;
}
}