Заголовок может быть немного запутанным, но я надеюсь, что просмотр кода прояснит его.
Предположим, у меня есть метод, чтобы проверить, существует ли ключ массива, и вернуть значение
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");
over
$this->bar = $array->getValue("FOO_BAR_1");
Или есть ли вообще более простой и отличный способ сделать то, что я пытаюсь сделать здесь?