thinkphp6: 自定義常量(php 8.1.1 / thinkphp v6.0.10LTS )


一,編寫php代碼

1,config/errorMsg.php
代碼:
<?php
//user
define('USER_NOT_EXIST', ['code'=>1001,'msg'=>'用戶不存在']);
define('USER_NOT_ACTIVE', ['code'=>1002,'msg'=>'用戶未激活']);
 
return [
    '0'     => '成功',
    '1000' => '不存在的請求地址',
    '1001' => '用戶名不存在',
    '1002' => '用戶未激活',
]; 
2,result/Result.php
<?php
namespace app\result;
use think\response\Json;
 
class Result {
    //success,返回數據
    static public function Success($data):Json {
        $rs = [
            'code'=>0,
            'msg'=>"success",
            'data'=>$data,
        ];
        return json($rs);
    }
    //error需要code/msg參數
    static public function ErrorCode($code,$msg):Json {
        $rs = [
            'code'=>$code,
            'msg'=>$msg,
            'data'=>"",
        ];
        return json($rs);
    }
    //error,傳入定義的數組常量
    static public function Error($arr):Json {
        $rs = [
            'code'=>$arr['code'],
            'msg'=>$arr['msg'],
            'data'=>"",
        ];
        return json($rs);
    }
}
3,controller/Goods.php  
使用常量
class Goods  extends BaseController
{
    /**
     * 商品詳情
     *
     * @return \think\Response
     */
    public function Detail(){
        //return Result::Error(USER_NOT_EXIST);
        return Result::Error(USER_NOT_ACTIVE);
    }
}

說明:劉宏締的架構森林是一個專注架構的博客,

網站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/05/29/thinkphp6-zi-ding-yi-chang-liang-php-8-1-1-thinkphp-v6-10lts/

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

說明:作者:劉宏締 郵箱: 371125307@qq.com

二,測試效果

三,查看php和thinkphp的版本:

php:
liuhongdi@lhdpc:/data/php/admapi$ php --version
PHP 8.1.1 (cli) (built: Dec 20 2021 16:12:16) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.1, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies 
thinkphp:
liuhongdi@lhdpc:/var/www/html$ cd /data/php/admapi/
liuhongdi@lhdpc:/data/php/admapi$ php think version
v6.0.10LTS 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM