在PHP中为函数返回逻辑错误的最佳做法是什么

时间:2017-10-13 14:27:33

标签: php error-handling

我想检查用户是否拥有员工权限。

function hasEmployeePermission($employeeID, $userKey)
{
    $usersID = DB::table('users')->where('key', $userKey)->value('id');

    if($userID != null) {
        $employeeID = DB::table('employees')->where('user_id', $userID)->value('id');

        if($mployeeID != null)
            return true;
        else
            return false;
    }
    return false;
}

我希望返回值更具表现力,例如抛出异常。我认为在逻辑错误中抛出异常不是最佳实践。我不知道如何修改代码以返回错误。

2 个答案:

答案 0 :(得分:0)

创建一个简单的错误类。

Class myError{
     public $error = true;
     public $message = null;
     function __construct($error,$message) {
         $this->error = $error;
         $this->message = $message;
     }
}

然后你可以做这样的事情,

    if($mployeeID != null)
        return new myError(true,"no permission");
    else
        return new myError(false,"has permission");

可以在课程中添加更多功能,例如在某处记录错误或类似的事情

答案 1 :(得分:0)

如果你想知道你的功能失败的原因,在这种情况下,我建议使用枚举。

以下是一个例子:

abstract class EmployeeErrors
{
    const WrongID = 1;
    const NoPermissions = 2;
    // etc.
}

function hasEmployeePermission($employeeID, $userKey)
{
    $usersID = DB::table('users')->where('key', $userKey)->value('id');

    if($userID != null) {
        $employeeID = DB::table('employees')->where('user_id', $userID)->value('id');

        if($mployeeID != null)
            return 0;
        else
            if ($userKey == null)
               return EmployeeErrors::WrongKey;
            else ...
    }
    return EmployeeErrors::WrongID;
}