【发布时间】:2018-12-04 09:33:20
【问题描述】:
我已经构建了大型 php 应用程序,但我知道问自己一个问题:函数是否应该只返回一种数据类型和 null 或者是否可以返回更多数据类型。因为它现在不知何故开始觉得重新调整一个以上的数据类型(除了 null)很脏,因为它邀请您在函数调用之后编写这样的东西:
if(is_array($returnVariable)) {
// do something
} else if(is_int($returnVarable)) {
// do something else
}
从函数中只返回一件事或什么都不返回似乎更合乎逻辑,因为您不必到处乱扔 if 和 else 代码。但我可能完全不在了。以这个函数为例:
public function update(array $data, Model $user)
{
if(!is_a($user, User::class)) return null;
//Update the user
$user->fill($data);
//Send the user an activated notification if it was activated and it was not earlier.
if($user->getOriginal('activated') == 0 && $user->activated == 1) {
$user->activated_at = Carbon::now()->toDateTimeString();
$user->notify(new ActivatedUserNotification($user));
}
$saved = $user->save();
//User was not updated because of an error
if(!$saved) return null;
//User was successfully updated. Return the user
return $user;
}
我实际上想返回一件事或 null。我这样做了。但由于我返回多个空值,我无法获得具体信息,为什么它在我调用该函数的地方返回空值。或者这可能表明该功能违反了诸如关注点分离原则之类的东西?我还有其他类似的情况,所以请不要太具体地解决这个特定的功能。
【问题讨论】:
标签: php design-patterns architecture return-type