我想知道在方法参数中使用类型提示是否有任何区别,例如:
function xyz (UserRepository $repo)
并用注解做同样的事情:
function xyz ($repo)
/* @var UserRepository $repo */
最佳答案
使用 type hint喜欢
function xyz (UserRepository $repo)
是编译器将理解并使用react的指令。这意味着,当您尝试传递任何不是 UserRepository
的内容时,PHP 将引发错误。
引用自 PHP 手册:
Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
使用“注释”只是文档。这只是对您的 IDE 和开发人员的提示。它在执行 PHP 时没有功能意义。用户可以将他想要的任何内容传递给函数,例如
$somethingElse = new SomethingElse;
xyz($somethingElse);
这会起作用,但是当尝试访问属于 UserRespository
的 $somethingElse
上的方法时它将失败。使用类型提示,您会提前失败。
注意:我将注解放在引号中,因为它并不是您从其他语言(如 Java)了解到的真正的注解。从 7.2 开始,PHP 没有注释。 Userland 实现虽然存在。
首选实型提示。
顺便说一下,这不是 Laravel 特有的东西。类型提示是原生 PHP 功能。
关于Laravel 中的 PHP 类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47195387/