How can the issue of hard-coded object creation be avoided when populating an array of Weapon objects in a Player's Inventory class in PHP?

Issue: Hard-coded object creation in an array of Weapon objects can be avoided by using a factory method or dependency injection to create the objects. This allows for more flexibility in creating different types of Weapon objects without directly instantiating them in the Inventory class.

// Using a factory method to create Weapon objects in Player's Inventory class

class WeaponFactory {
    public static function createWeapon($type) {
        switch($type) {
            case 'sword':
                return new Sword();
            case 'axe':
                return new Axe();
            // Add more cases for other types of weapons
            default:
                throw new Exception('Invalid weapon type');
        }
    }
}

class Inventory {
    private $weapons = [];

    public function addWeapon($type) {
        $this->weapons[] = WeaponFactory::createWeapon($type);
    }
}

// Example usage
$playerInventory = new Inventory();
$playerInventory->addWeapon('sword');
$playerInventory->addWeapon('axe');