处理PHP 7返回类型的正确方法 [英] Correct way to handle PHP 7 return types

查看:182
本文介绍了处理PHP 7返回类型的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正忙于创建应用程序,我想使用PHP 7返回类型.现在,我在php.net上阅读到,这是一个设计决定,当定义返回类型时,不允许返回null.

I'm busy creating an application and i want to use the PHP 7 return types. Now I read on php.net that it was a design decision that it is not allowed to return null when a return type is defined.

处理此问题的正确方法是什么?

What is the correct way too handle this?

一个选项是try ... catch块:

One option is a try...catch block:

public function getMyObject() : MyObject
{ 
     return null;
}

try
{
    getMyObject();
}
catch(Exception $e)
{
    //Catch the exception
}

对此我感觉不太好,因为我的代码将是一个巨大的try ... catch块,因为我需要为每个返回对象的方法编写一个try ... catch块.

I don't have a good feeling about this, because my code will be a huge try...catch block since I need to write a try...catch block for every method that returns an object.

空对象模式是一个很好的解决方案,但我不喜欢创建NullObject对于我的应用程序中的每个对象. 有正确的方法吗?

The Null Object Pattern is a good solution for this, but I don't like the idea to create a NullObject for each object in my application. Is there correct way to do this?

推荐答案

对此我感觉不太好,因为我的代码将是一个巨大的try/catch块,因为我需要为每个返回对象的方法编写一个try/catch块.

I don't have a good feeling about this, because my code will be a huge try/catch block since I need to write a try / catch block for every method that returns an object.

(使用您的代码)替代方法是始终检查null的返回值,以免由于使用null作为对象而出错.

The alternative (with your code) would be to always check the returned value for null to not get errors from using null as an object.

使用异常更具表现力,并且使bug尽早可见,这是一件好事.因此,请确保您的方法始终返回对象,或者如果无法履行其合同,则引发异常.否则,返回类型没有实际值.

Using exceptions is more expressive and makes bugs visible early, which is a good thing. So either make sure that your method always returns an object or throw an exception if it cannot fulfil its contract. Otherwise the return type has no real value.

这篇关于处理PHP 7返回类型的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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