Laravel 中的 PHP 类型提示

标签 php laravel

我想知道在方法参数中使用类型提示是否有任何区别,例如:

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/

相关文章:

javascript - 无法从expressJS中的HTML表单获取数组

php - ReflectionFunction 的 isDeprecated 是如何工作的?

javascript - piwik 无法在 HTTPS 中工作

php - 如何从 laravel mongodb 的结果集中删除主键?

php - 如何编写与 laravel 相同的 DD() 函数?

php - 如何在没有 mbstring 扩展名的情况下处理 PHP 中的 unicode

php - 这是什么类型的数据类型,我如何在查询中使用它?

php - MySQL LIKE + php sprintf

php - Laravel Horizo​​n Assets 中出现 404

laravel - Bootstrap Striped-table 不适用于 Vuejs