Extra Objects
Jonathan Daggerhart edited this page Sep 23, 2015
·
1 revision
This section is to give you an overview of most basic aspects of objects.
Objects are a way of encapsulating or compartmentalizing variables and functions to keep them from conflicting with or overwriting other variables and functions that may be used in your script.
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects". In OOP programming, programs are designed by making them out of objects that interact with one another.
An object starts with a class. A class may contain it's own constants, variables (called "properties"), and functions (called "methods").
Simple Class definition:
class Player
{
// property declaration
public $hitPoints = 100;
// method declaration
public function getHitPoints() {
return $this->hitPoints;
}
public function takeDamage( $damage ){
$this->hitPoints -= $damage;
}
}
To create an instance of a class, the new keyword must be used.
Example: Creating multiple instances of the Player class.
$playerOne = new Player();
$playerOne->takeDamage( 12 );
$playerTwo = new Player();
$playerTwo->takeDamage( 55 );
echo $playerOne->getHitPoints();
// 88
echo $playerTwo->getHitPoints();
// 45