PHP-返回匿名类或使用方法

问题描述 投票:0回答:1

标题可能有些混乱,但是我希望通过查看代码来澄清它。

假设我有一种检查数组键是否存在并返回值的方法

class Foo {
    private $bar1;
    private $bar2;

    public function __construct($file) {
        $array = $this->decodeFile($file);

        $this->bar = $this->getValue($array, "FOO_BAR_1");
        $this->bar = $this->getValue($array, "FOO_BAR_2");
    }

    private function decodeFile($file) {
        // ignoring file checks for the example
        return json_decode(file_get_contents($file), true);
    }

    private function getValue($array, $key) {
        if (!array_key_exists($key, $array)) {
            return null;
        }

        return $array[$key];
    }
}

但是getValue方法并不是真的感觉像Foo的一部分,(只是我的看法)。所以我想到了一个匿名类替代方法:

class Foo {
    private $bar1;
    private $bar2;

    public function __construct($file) {
        $array = $this->decodeFile($file);

        $this->bar = $array->getValue("FOO_BAR_1");
        $this->bar = $array->getValue("FOO_BAR_2");
    }

    private function decodeFile($file) {
        return new class($file) {
            private $array;

            public function __construct($file) {
                // ignoring file checks for the example
                $this->array = json_decode(file_get_contents($file), true);
            }

            public function getValue($key) {
                 if (!array_key_exists($key, $array)) {
                     return null;
                 }

                return $array[$key];
            }
        }
    }
}

因此,最后,我认为这是值得考虑的事情,是因为(可能不是)的微小差异

$this->bar = $this->getValue($array, "FOO_BAR_1");

超过

$this->bar = $array->getValue("FOO_BAR_1");

或者还有甚至更完整,更简单且完全不同的方式来做我在这里要做的事情?

php oop methods anonymous-class
1个回答
0
投票

[如@KoalaYeung的注释中所述,为此目的使用空合并算子(??)是合适的。

空合并合并运算符(??)已添加为语法糖,用于通常需要将三元数与isset()结合使用的常见情况。如果它存在且不为NULL,则返回其第一个操作数;否则返回第一个操作数。否则返回第二个操作数。 -PHP Manual

发现了一个有用的小功能。

因此$this->bar = $array['FOO_BAR_1'] ?? NULL确实将是一个更简单,更易读的解决方案

© www.soinside.com 2019 - 2024. All rights reserved.