【问题标题】:PHP - Avoid writting nested if statementPHP - 避免编写嵌套的 if 语句
【发布时间】:2021-09-27 13:18:59
【问题描述】:

我有这个变量:

$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'];
}

什么是更短更好更易读的方式来编写这段代码?

【问题讨论】:

标签: php variables coding-style isset php-5.6


【解决方案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();

【讨论】:

  • 虽然它不像问的那样短,但它更好、更健壮——我喜欢它!也许在调用 -> test() 时传递 dat/request/response 参数名会更好。
  • 是的,IRL 你显然会做这样的事情。
  • 实际提取值的代码更短——只有一行。如果您要提取多个值,将其包装在一个函数中会更容易使用(并且需要更少的整体代码)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多