Classes and Objects in PHP
Introduction to Classes and Objects
In PHP, classes and objects are the foundation of Object-Oriented Programming (OOP).
A class is a blueprint or template that defines the structure (properties and methods) of an object.
An object is an instance of a class that holds actual data and can perform actions.
Example: Basic Class and Object
class Car {
// Properties (attributes)
public $model;
public $color;
// Method (function)
public function startEngine() {
return "The $this->model's engine is running!";
}
}
// Creating an object (instance of Car)
$myCar = new Car();
$myCar->model = "Toyota Camry";
$myCar->color = "Red";
echo $myCar->startEngine(); // Output: The Toyota Camry's engine is running!
Properties (Class Variables)
Properties are variables inside a class that store data.
They can have access modifiers: public, private, or protected.
public properties can be accessed from anywhere.
Example: Class Properties
class Person {
public $name; // Public property
private $age; // Private property (only accessible inside the class)
protected $email; // Protected property (accessible in child classes)
public function setAge($age) {
$this->age = $age;
}
public function getAge() {
return $this->age;
}
}
$person = new Person();
$person->name = "John Doe"; // OK (public)
$person->setAge(25); // Sets private property via method
echo $person->getAge(); // Gets private property (Output: 25)
// $person->age = 30; // Error (private property cannot be accessed directly)
Methods (Class Functions)
Methods are functions defined inside a class that define its behavior.
Example: Class Methods
class Calculator {
public function add($a, $b) {
return $a + $b;
}
public function subtract($a, $b) {
return $a - $b;
}
}
$calc = new Calculator();
echo $calc->add(5, 3); // Output: 8
echo $calc->subtract(10, 4); // Output: 6
The $this Keyword
$this refers to the current object inside a class.
It is used to access properties and methods within the same class.
Example: Using $this
class User {
public $username;
public function setUsername($name) {
$this->username = $name;
}
public function greet() {
return "Hello, $this->username!";
}
}
$user = new User();
$user->setUsername("Alice");
echo $user->greet(); // Output: Hello, Alice!
Constructor (__construct())
A constructor is a special method that automatically runs when an object is created.
Used to initialize properties or perform setup tasks.
Example: Constructor
class Book {
public $title;
public $author;
// Constructor
public function __construct($title, $author) {
$this->title = $title;
$this->author = $author;
}
public function getInfo() {
return "$this->title by $this->author";
}
}
// Creating an object with constructor parameters
$book = new Book("PHP OOP Guide", "John Smith");
echo $book->getInfo(); // Output: PHP OOP Guide by John Smith
Destructor (__destruct())
A destructor is called when an object is destroyed (script ends or unset() is called).
Used for cleanup tasks (e.g., closing database connections).
Example: Destructor
class FileHandler {
public function __construct() {
echo "File opened.
";
}
public function __destruct() {
echo "File closed.
";
}
}
$file = new FileHandler();
// Output when script ends:
// File opened.
// File closed.
Static Properties and Methods
Static properties/methods belong to the class itself, not individual objects.
Accessed using :: (scope resolution operator).
Example: Static Members
class Counter {
public static $count = 0;
public static function increment() {
self::$count++;
}
}
Counter::increment();
Counter::increment();
echo Counter::$count; // Output: 2
Comparing Classes and Objects
Feature | Class | Object |
---|---|---|
Definition | Blueprint or template | Instance of a class |
Memory | No memory allocation | Allocates memory when created |
Usage | Declared once with class | Created with new ClassName() |
Example | class Car { ... } | $myCar = new Car() |
Real-World Example: User Management System
class User {
private $username;
private $email;
public function __construct($username, $email) {
$this->username = $username;
$this->email = $email;
}
public function getUsername() {
return $this->username;
}
public function getEmail() {
return $this->email;
}
}
// Creating user objects
$user1 = new User("alice123", "alice@example.com");
$user2 = new User("bob456", "bob@example.com");
echo $user1->getUsername(); // Output: alice123
echo $user2->getEmail(); // Output: bob@example.com
Conclusion
- Classes define structure, objects are instances of classes
- Properties store data, methods define behavior
- Constructors initialize objects, destructors clean up
- Static members belong to the class, not objects