在 php 中,我应该在通常返回数组的方法中返回 false、null 还是空数组? [英] In php, should I return false, null, or an empty array in a method that would usually return an array?

查看:81
本文介绍了在 php 中,我应该在通常返回数组的方法中返回 false、null 还是空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了几个对此的回应,但没有一个与 PHP(这是一种非常弱的类型语言)有关:

I've found several responses to this, but none pertaining to PHP (which is an extremely weak typed language):

关于PHP,在一个通常会返回数组但发生失败的方法中返回false、null或空数组是否合适?

With regards to PHP, is it appropriate to return false, null, or an empty array in a method that would usually return an array, but has a failure occur?

换句话说,如果另一个开发人员加入我的项目,他们希望看到什么?

In other words, if another developer jumped in on my project, what would they expect to see?

推荐答案

数组是事物的集合.空数组表示一切正常,只是该集合中什么都没有".如果您确实想发出错误的信号,则应返回false.由于 PHP 是动态类型的,根据您的需要,很容易严格或松散地检查返回值:

An array is a collection of things. An empty array would signal that "everything went fine, there just isn't anything in that collection". If you actually want to signal an error, you should return false. Since PHP is dynamically typed, it's easy to check the return value either strictly or loosely, depending on what you need:

$result = getCollection();

if (!$result)           // $result was false or empty, either way nothing useful
if ($result === false)  // an actual error occurred
if ($result)            // we have an array with content

异常情况下也有异常用于错误报告.这实际上取决于功能的职责和错误的严重程度.如果函数的作用允许响应empty collection"和nope"同等,上面的可能没问题.然而,如果函数根据定义必须始终返回一个集合(即使它是空的)并且在某些情况下它不能,那么抛出异常可能比返回 false 更合适.

There are also exceptions for error reporting in exceptional cases. It really depends on the responsibilities of the function and the severity of errors. If the role of the function allows the response "empty collection" and "nope" equally, the above may be fine. However, if the function by definition must always return a collection (even if that's empty) and in certain circumstances it cannot, throwing an exception may be a lot more appropriate than returning false.

这篇关于在 php 中,我应该在通常返回数组的方法中返回 false、null 还是空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆