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 some common mistakes to avoid when trying to find the latest record in a database using PHP?
- How can including a file with the ID of a business in PHP be a useful solution for database updates?
- How can PHP developers ensure that the correct values are displayed in selection boxes when retrieving data from a database, as described in the forum thread?