Classes and Objects in php
php supports Object-Oriented Programming (OOP). A class is a blueprint for objects. An object is an instance of a class.
Defining a Class
<?php
class Car {
public $brand;
public $color;
public $speed = 0;
public function accelerate($amount) {
$this->speed += $amount;
}
public function getSpeed() {
return $this->speed;
}
}
?>
Creating Objects
<?php
$car1 = new Car();
$car1->brand = "Toyota";
$car1->color = "Red";
$car1->accelerate(60);
echo $car1->brand; // Toyota
echo $car1->getSpeed(); // 60
?>
The Constructor
The __construct() method is automatically called when an object is created:
<?php
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function introduce() {
echo "Hi, I'm {$this->name} and I'm {$this->age} years old.";
}
}
$person = new Person("Alice", 30);
$person->introduce();
// Hi, I'm Alice and I'm 30 years old.
?>
The Destructor
Called automatically when an object is destroyed or the script ends:
<?php
class Logger {
public function __construct() {
echo "Logger started.<br>";
}
public function __destruct() {
echo "Logger destroyed.<br>";
}
}
$log = new Logger(); // Logger started.
// Logger destroyed. (at end of script)
?>
Access Modifiers
| Modifier | Accessible From |
|---|---|
public | Anywhere |
protected | Class and subclasses |
private | Only within the class |
<?php
class BankAccount {
public $owner;
protected $balance;
private $pin;
public function __construct($owner, $balance, $pin) {
$this->owner = $owner;
$this->balance = $balance;
$this->pin = $pin;
}
public function getBalance() {
return $this->balance;
}
}
$acc = new BankAccount("Alice", 10000, 1234);
echo $acc->owner; // Alice
echo $acc->getBalance(); // 10000
// echo $acc->pin; // Error: private
?>