首页 > 解决方案 > 空返回值

问题描述

我想做一个函数来获取交易代码,但返回值为空。

我从我的模型中调用这个函数。

public function getTransactionCode($type){

    switch($type)
    {
        case '52';
        $count = $this->where('type_id',$type)
                    ->count('id');
        $next = (intval($count) ?: 0) + 1;
        $code = "LAP-00{$next}";
        return $code;

        case '53';
        $count = $this->where('type_id',$type)
                    ->count('id');
        $next = (intval($count) ?: 0) + 1;
        $code = "PC-00{$next}";
        return $code;

        case '54';
        $count = $this->where('type_id',$type)
                    ->count('id');
        $next = (intval($count) ?: 0) + 1;
        $code = "TAB-00{$next}";
        return $code;

        case '55';
        $count = $this->where('type_id',$type)
                    ->count('id');
        $next = (intval($count) ?: 0) + 1;
        $code = "OOE-00{$next}";
        return $code;

    }
  
}

我想在我的控制器上使用这个功能从我的模型中提取任何值。

 $code = $this->equipment->getTransactionCode($type = '');

但它一直返回空值。

标签: phplaravellaravel-4switch-statement

解决方案


正如@shaedrich 建议的那样,switch不返回任何内容。但是,您可以为变量赋值,然后在switch语句之后返回。

也应该有冒号(:)case不是分号(;)

public function getTransactionCode($type){
    $code = 'ANY DEFAULT VALUE'; // Needs to set any desired value here

    switch($type)
    {
        case '52':
        $count = $this->where('type_id',$type)
                    ->count('id');
        $next = (intval($count) ?: 0) + 1;
        $code = "LAP-00{$next}";
        break;

        case '53':
        $count = $this->where('type_id',$type)
                    ->count('id');
        $next = (intval($count) ?: 0) + 1;
        $code = "PC-00{$next}";
        break;

        case '54':
        $count = $this->where('type_id',$type)
                    ->count('id');
        $next = (intval($count) ?: 0) + 1;
        $code = "TAB-00{$next}";
        break;

        case '55':
        $count = $this->where('type_id',$type)
                    ->count('id');
        $next = (intval($count) ?: 0) + 1;
        $code = "OOE-00{$next}";
        break;
    }
    
    return $code;
}

推荐阅读