php - PHP - 避免编写嵌套的 if 语句
问题描述
我有这个变量:
$otcId;
可以从 3 个不同的地方检索哪个值(请记住,这个值在所有地方总是相同的):
$otcId = $this->dat['id_rfcOV'];
$otcId = $this->request['id_rfcOV'];
$otcId = $this->response['id_rfcOV'];
我的方法如下:
$otcId = $this->dat['id_rfcOV'];
if(isset($this->dat['id_rfcOV'])){
$otcId = $this->dat['id_rfcOV'];
} elseif(isset($this->request['id_rfcOV'])) {
$otcId = $this->request['id_rfcOV'];
} elseif(isset($this->response['id_rfcOV'])) {
$otcId = $this->response['id_rfcOV'];
}
编写此代码的更短更好且更易读的方法是什么?
解决方案
如果我是你,我会将它包装在一个函数中,并使用null 合并运算符来简化检索和默认值的返回。
<?php
class MyController
{
private array $dat = [];
private array $request = ['id_rfcOV' => 'foo'];
private array $response = ['id_rfcOV' => 'bar'];
/**
* @param string $name Parameter name
* @param null $default Default value to return if no matching parameters are found
* @return mixed|string|null
*/
function getParam(string $name, $default=null)
{
return $this->dat[$name] ?? $this->request[$name] ?? $this->response[$name] ?? $default;
}
function test(): void
{
// Using a member function, we can get our parameter value with a one-liner
$otcId = $this->getParam('id_rfcOV');
assert($otcId == 'bar', 'Value should be from the last array checked');
printf("Value is %s \n", $otcId);
$val = $this->getParam('non-existent', 'wombats');
assert($val == 'wombats', 'Value should be the default');
printf("Value is %s \n", $val);
}
}
$myController = new MyController();
$myController->test();
推荐阅读
- javascript - 编辑 Google Doc 然后转换为 PDF 的脚本
- flutter - 根据 Flutter 中的滚动位置更改容器的宽度
- scrapy - 带有“部署失败(400)”的scrapyd-deploy
- python - 如何在python中将行的每个元素转换为列?
- date - 在 DOM 中的日期之间变得不同
- html - h1、h2、h3 标签调整大小不同于 p 标签
- ruby-on-rails - 使用 Image_tag,如果加载失败,则呈现替代方案
- wordpress - 从本地 wordpress 迁移到服务器的问题
- java - 使用 Optional 简化许多 if 检查
- ios - 网站图像未从 Apple 设备 (Safari) 上的其他服务器加载