我有这个变量:
$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'];
}
编写这段代码的更短更好、更易读的方法是什么?
答案 0 :(得分:1)
如果我是你,我会把它包装在一个函数中,并使用 null coalescing operator 来简化检索和默认值的返回。
<?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();