Reputation:
I have a quick question regarding how to use classes. I am what I would call a beginner at programming and have set myself the task of creating a small web based game to learn. In the game I want to have various unit types (i.e. Swordsman, Cavalry, Archer). I have been told that I should create a separate class for each type of unit however I have also been told to create one class like "class unit". Which is the correct way to use classes? I apologise if this is vague but I can't think of a better way to word it. Having searched this site for other class related questions, they don't seem to cover this type of usage.
class unit {
$unitName = "";
$unitSpeed = "";
$unitHealth = "";
$unitDamage = "";
}
or
class archer {
$archerSpeed = "";
$archerHealth = "";
$archerDamage = "";
}
class cavalry {
$cavalrySpeed = "";
$cavalryHealth = "";
$cavalryDamage = "";
}
Upvotes: 0
Views: 39
Reputation: 410
the better way i sto organize your code, like this:
abstract class Unit
{
public $speed=0;
public $health=0;
public $damage=0;
}
class Archer extends Unit
{
}
class Wizard extents Unit
{
public $mana;
}
class ArcherAdvanced extends Unit
{
public function __construct()
{
$this->health = 4;
}
}
With this structure You must always use a specific class, but implementing that can be very easy. It's also easy to add some property for different usage (like wizard).
U can use this in other class like this:
class Game
{
public function run()
{
$gandalf = new Wizard();
$legolas = new Archer();
// then fight!!
}
}
I hope this can be helpful. However i suggest to take a look here: http://www.phptherightway.com/
In the class ArcherAdvanced , when you use it, and do new ArcherAdvanced(), yuou automatically set health to value = 4.
Upvotes: 2
Reputation: 46
One way to do what you want would be to use subclasses. See here: http://php.net/manual/en/language.oop5.inheritance.php
You would make a base class called "unit" that would contain all of the information that is common between all types of units.
Then you would make a class for each type of unit that contains any logic that makes this type of unit different from the others.
With this approach, you are being "DRY" by not repeating code that is common for all units (which would probably happen with 3 different classes), and yet flexible in case there are differences between them whose code belongs in the class file (Where using only one "unit" class you might have to use conditionals to accomplish the same thing).
Here is what the base code might look like:
class Unit {
//Defaults for all units
$unitName = "";
$unitSpeed = "1";
$unitHealth = "1";
$unitDamage = "1";
}
class Archer extends Unit{
$unitName = "archer";
}
class Cavalry extends Unit {
$unitName = "cavalry";
}
Upvotes: 0