方法返回值不一致
这其实是一个哲学问题。 我使用 PHP 作为一种语言进行编程已经一年了,正如大家所知,PHP 对于数据类型非常自由。 我想知道:鉴于此,允许方法返回不同类型的值是一个好习惯吗? 示例:我习惯于设置应该以默认值(通常为 false)返回的变量,如果在方法执行期间一切顺利,则该变量将获取成功执行所给出的值。 免责声明:我尝试使用 PHPDoc 记录所有内容。
This is a philosophical question, actually.
It's been a year I'm programming using PHP as a language and, as all of you know, PHP is very liberal as for the datatypes.
I was wondering: given that, is it a good practice to allow methods to return different kind of values?
Example: I'm used to set the variable that should be returned at a default value (usually false) and, if during the execution of the method everything goes well, the variable gets the value the successful execution has given.
Disclaimer: I try to document everything using PHPDoc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
似乎是正确的方法:返回布尔 false 允许方法/函数返回其他逻辑“假”值,例如 0 或空字符串作为有效值,同时仍然允许调用者使用
=== 运算符。
Seems like a correct approach: returning boolean false allows the method/function to return other logical "false" values such as 0 or the empty string as valid while still allowing the caller to check its result with the
===
operator.这是一种常见的方法,至少在 PHP 中是这样,而且这并不是一个坏习惯。
使用 PHPDoc 约定可以毫无问题地记录它: http:// Manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.return.pkg.html
It's a common approach, at least in PHP, and it isn't a bad practice.
It can be documented without problem using the PHPDoc convention: http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.return.pkg.html
不,不是。 PHP 中不行,其他语言中不行。最好为特定类型的结果添加其他方法。
No, it's not. Not in PHP not in other languages. Better add an other method for a specific type of results.