【问题标题】:How to define return type in PHP and handle the Exceptions?如何在 PHP 中定义返回类型并处理异常?
【发布时间】:2022-10-06 08:06:57
【问题描述】:

我想在 PHP 中定义方法的返回类型(特别是在 Laravel 中) 例如,通过 Id 获取模型:

public function show(int $id) {
    try{
         $student = Student::first($id);
         return $student;
        }
    catch(Exception $exp){
        throw Exception($exp)
        }
}

代码可以正常工作,但是当我尝试在方法前面定义返回类型(本例中为学生)时:

public function show(int $id) : Student

我收到错误消息,指出显式返回类型与方法的返回值不匹配。

如何定义返回类型并处理异常?

  • 请问异常处理的意义何在?您可以使用Student::firstOrFail($id),这将引发错误并强制返回 JSON 响应,表示未找到提供的 ID 的实体。如果您真的想处理异常(first() 不会抛出任何异常,因为如果查询返回空则返回 null),您可以从数据库中选择学生,然后进行检查以验证学生是否是否为空(if (is_null($student) { ... }if (!($student instanceof Student)) { ... }),如果它抛出 StudentNotFoundException(创建它)。
  • 此片段代码只是一个示例。我询问了具有各种可能返回类型的任何其他复杂情况。如果我创建 StudentNotFoundException,我仍然无法定义返回类型,对吗?
  • 您可以在函数上方添加/** @throws StudentNotFoundException */,以便IDE 会警告您在何处调用相同的函数。异常不是返回类型,您可以像现在一样继续返回Student (/** * @return Student * @throws StudentNotFoundException * @throws AnotherException */)

标签: php laravel exception


【解决方案1】:

使用find() 方法而不是first()... 为什么?让我们来看看:

// This code
User::first($id);
// is equivalent to this SQL statement:
select `5` from `users` limit 1 
//which causes unknown column name 

// This code
User::find($id);
// is equivalent to this SQL statement:
select * from `users` where id = $id limit 1 
//which retrieves the first matching student by id and it's the correct way!

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多