Welcome! Today, we're exploring PHP classes, a fundamental aspect of Object-Oriented Programming (OOP) in PHP. Using practical examples, we'll delve into the essential concepts of PHP classes, including their structure, attributes, and methods.
PHP Classes Refresher
Class Attributes
Class Methods
Examples of PHP Classes, Attributes, and Methods
Lesson Summary
Excellent work exploring PHP classes, their attributes, and methods. PHP classes help you organize your code, enhancing its readability and manageability. Now, challenge your understanding with practice exercises to reinforce your refreshed knowledge. Happy coding!
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Let's kick off with a look at PHP classes. Crucial in OOP, PHP classes encapsulate related data and functions within a compact unit called an object. Think of a video game character as an instance of a class, with specific attributes (like health or strength) and methods (such as attack or defense).
A PHP class acts as a blueprint containing attributes and methods. Attributes represent data pertinent to a class instance, while methods are functions or actions that manipulate this data. Each class comes with a constructor, which is responsible for initializing class attributes.
In PHP, the $this keyword is essential for accessing the class instance's attributes and methods. When a new class instance is instantiated, $this allows the object to maintain its state and behaviors.
PHP
<?phpclass GameCharacter { // Attributes public $name; public $health; public $strength; // Constructor public function __construct($name, $health, $strength) { $this->name = $name; $this->health = $health; $this->strength = $strength; } // Method public function attack($otherCharacter) { $otherCharacter->health -= $this->strength; }}?>
Note: we will cover constructors in the next unit of this course, but in the meantime, consider them just as methods that construct the instance of your class given certain input parameters!
Attributes in PHP classes store data associated with each instance. In our GameCharacter class, name, health, and strength are such attributes. You can access a class attribute with an instance of the class, followed by an arrow (->), and the attribute name.
Attributes are initialized within the constructor. PHP uses the $this keyword to refer to the current object instance and set attribute values.
PHP
<?phpclass GameCharacter { // Attributes public $name; public $health; public $strength; // Constructor public function __construct($name, $health, $strength) { $this->name = $name; $this->health = $health; $this->strength = $strength; }}$character = new GameCharacter("Hero", 100, 20); // instance of the classecho $character->name . "\n"; // prints: Heroecho $character->health . "\n"; // prints: 100echo $character->strength . "\n"; // prints: 20?>
Here, the constructor initializes the class attributes with provided arguments, differentiating one class instance from another and maintaining the instance's state.
PHP classes also contain methods — functions that manipulate class data. For instance, the attack method in the GameCharacter class simulates an attack by one character on another.
PHP
<?phpclass GameCharacter { // Attributes public $name; public $health; public $strength; // Constructor public function __construct($name, $health, $strength) { $this->name = $name; $this->health = $health; $this->strength = $strength; } // Method public function attack($otherCharacter) { $otherCharacter->health -= $this->strength; }}$character1 = new GameCharacter("Hero", 100, 20); // First instance$character2 = new GameCharacter("Villain", 80, 15); // Second instanceecho $character2->health . "\n"; // prints: 80$character1->attack($character2); // character1 attacks character2echo $character2->health . "\n"; // prints: 60, health decreased after the attack?>
To further our understanding of PHP classes, let's build a BankAccount class. This will help us model real-world entities using OOP by defining attributes like an account holder's name and balance alongside methods for depositing and withdrawing money.
PHP
<?phpclass BankAccount { // Attributes public $holderName; public $balance; // Constructor with a default balance of 0 public function __construct($holderName, $balance = 0) { $this->holderName = $holderName; $this->balance = $balance; } // Method to deposit money public function deposit($amount) { if ($amount > 0) { $this->balance += $amount; echo "$amount deposited. New balance: $this->balance\n"; } else { echo "Deposit amount must be positive.\n"; } } // Method to withdraw money public function withdraw($amount) { if ($amount > 0 && $amount <= $this->balance) { $this->balance -= $amount; echo "$amount withdrawn. Remaining balance: $this->balance\n"; } else { echo "Insufficient balance for the withdrawal or amount is not positive.\n"; } }}$account = new BankAccount("Alex", 1000); // An account with an initial balance of 1000// Perform some transactions$account->deposit(500);// Deposit money, prints: 500 deposited. New balance: 1500$account->withdraw(200);// Withdraw money, prints: 200 withdrawn. Remaining balance: 1300echo "Final balance in {$account->holderName}'s account: {$account->balance}\n";// prints: Final balance in Alex's account: 1300?>
This example further highlights how classes encapsulate data (attributes) and functionalities (methods), enabling the emulation of real-world scenarios. The BankAccount class facilitates the creation of objects representing bank accounts, showcasing the powerful organizational benefits of using classes in PHP.