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

问题描述 投票:0回答:2

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

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

代码没有问题,但是当我尝试在方法前面定义返回类型(本例中为 Student)时:

public function show(int $id) : Student

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

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

php laravel exception
2个回答
0
投票

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!

0
投票

由于您的方法可能会返回不同类型的数据,因此您应该在定义返回类型之前使用安全运算符。

例子

public function show():?Student { 
    // body 
}

或者明确地,您可以使用 PHP 中的竖线

(|)
字符为您的方法定义两个以上的返回类型。

例子

public function show(): Student|Exception { 
   // body 
}

在上面的示例中,您只是提到

show()
方法可以返回一个
Student
对象或一个
Exception
对象。

© www.soinside.com 2019 - 2024. All rights reserved.