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');
Keywords
Related Questions
- What are the best practices for separating programming and HTML code when using PHP?
- What steps can be taken to troubleshoot the "php_network_getaddresses: getaddrinfo failed: Host unknown" error when connecting to a database in PHP?
- How can strtotime() function be used to convert date formats in PHP?