PhpStorm - 参数的 PHPDoc "any" 类型
PhpStorm - PHPDoc "any" type for parameters
我来自严格类型化的编程语言,它有一个名为 "ANY".
的类型
因为 PHP 是松散耦合的,我的 PhpDoc 需要某种类型提示,说明变量、参数或 return 值可以是任何类型。目前我必须写这样的东西:
@var string|int|bool|array|object $someVariable
这会让我的生活更轻松,如果我能改写的话代码会更容易阅读:
@var any $someVariable
我实际上在很多情况下都遇到过这个问题 - 在过去的几个月里已经超过 20-30 次了,因为我使用了 PhpStorm,它向我显示警告说某些方法需要其他类型的参数类型,要么是因为我忘记将它明确地放在类型列表中,要么是因为我使用的是用 Eclipse 编写的代码,它没有为我自称的 "any" 类型显示任何警告。
我的问题:有没有办法告诉 PhpStorm 当我说 any
我实际上是指 string|any|bool|array|object
或者是否有其他类型的提示这样说?我也很好奇是否只有我有这个问题,或者是否有其他人也这样。
你应该使用 "mixed"。 PHP7.0 还有参数和 return 值的实际类型提示。
你有两个问题,我有两个答案。您问的是在涉及多个 return 类型时什么是好的做法。一个好的做法是根本不这样做。 (始终)确保您的方法只有 return 一种类型。这不仅会使您的方法更清晰,而且调用该方法的代码也会更清晰;您永远不必检查类型,并且您始终知道作为 return 值会得到什么,因此您将知道可以用它做什么。拥有一些架构技能,这并不是一个很难实现的实践。
PHP
Pseudo-types and variables
mixed
mixed
indicates that a parameter may accept multiple (but not necessarily all) types.
gettype()
for example will accept all PHP types, while str_replace()
will accept strings and arrays.
PHP文档
mixed
, the element to which this type applies can be of any type as specified here. It is not known on compile time which type will be use.
— PSR-5
例子
/**
* Counts the number of items in the provided array.
*
* @param mixed[] $items Array structure to count the elements of.
*
* @return int Returns the number of elements.
*/
function count(array $items)
{
<...>
}
我来自严格类型化的编程语言,它有一个名为 "ANY".
的类型因为 PHP 是松散耦合的,我的 PhpDoc 需要某种类型提示,说明变量、参数或 return 值可以是任何类型。目前我必须写这样的东西:
@var string|int|bool|array|object $someVariable
这会让我的生活更轻松,如果我能改写的话代码会更容易阅读:
@var any $someVariable
我实际上在很多情况下都遇到过这个问题 - 在过去的几个月里已经超过 20-30 次了,因为我使用了 PhpStorm,它向我显示警告说某些方法需要其他类型的参数类型,要么是因为我忘记将它明确地放在类型列表中,要么是因为我使用的是用 Eclipse 编写的代码,它没有为我自称的 "any" 类型显示任何警告。
我的问题:有没有办法告诉 PhpStorm 当我说 any
我实际上是指 string|any|bool|array|object
或者是否有其他类型的提示这样说?我也很好奇是否只有我有这个问题,或者是否有其他人也这样。
你应该使用 "mixed"。 PHP7.0 还有参数和 return 值的实际类型提示。
你有两个问题,我有两个答案。您问的是在涉及多个 return 类型时什么是好的做法。一个好的做法是根本不这样做。 (始终)确保您的方法只有 return 一种类型。这不仅会使您的方法更清晰,而且调用该方法的代码也会更清晰;您永远不必检查类型,并且您始终知道作为 return 值会得到什么,因此您将知道可以用它做什么。拥有一些架构技能,这并不是一个很难实现的实践。
PHP
Pseudo-types and variables
mixed
mixed
indicates that a parameter may accept multiple (but not necessarily all) types.
gettype()
for example will accept all PHP types, whilestr_replace()
will accept strings and arrays.
PHP文档
mixed
, the element to which this type applies can be of any type as specified here. It is not known on compile time which type will be use.— PSR-5
例子
/**
* Counts the number of items in the provided array.
*
* @param mixed[] $items Array structure to count the elements of.
*
* @return int Returns the number of elements.
*/
function count(array $items)
{
<...>
}