<?php class Car { protected Supplier $supplier; public function __construct() { $this->supplier = new Supplier(); } final public function getSupplier(): Supplier { return $this->supplier; } } class Supplier { const SUPPLIERS = [ 1 => 'toyota', 2 => 'bmw' ]; private $id; private $name; final public function set(mixed $value): void { if (is_int($value)) { $this->id = $value; $this->name = self::SUPPLIERS[$value]; } elseif (is_string($value)) { $this->name = $value; $this->id = array_search($value, self::SUPPLIERS); } else { throw new \InvalidArgumentException('Invalid value:' . $value); } } public function setByName(string $name) { $this->name = $name; $this->id = array_search($name, self::SUPPLIERS); } public function getId(): int { return $this->id; } public function getName(): string { return $this->name; } } $car = new Car(); // IdのセットでNameも自動でセットされる $car->getSupplier()->set(1); echo $car->getSupplier()->getId() . PHP_EOL; // 1 echo $car->getSupplier()->getName() . PHP_EOL; // toyota // NameのセットでIdも自動でセットされる $car->getSupplier()->set('bmw'); echo $car->getSupplier()->getId() . PHP_EOL; // 2 echo $car->getSupplier()->getName() . PHP_EOL; // bmw
You have javascript disabled. You will not be able to edit any code.