PHP Classes and Objects — Complete Guide to OOP in PHP
In this tutorial, you will learn about PHP Classes and Objects. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP classes define blueprints for objects, encapsulating data (properties) and behavior (methods) into reusable components following object-oriented programming principles.
What You'll Learn
By the end of this tutorial, you'll define classes, instantiate objects, use constructors and destructors, apply access modifiers, create static members, and understand OOP fundamentals.
Why OOP Matters
Object-oriented programming organizes code into logical, reusable units. It makes large applications maintainable by grouping related data and behavior, enabling inheritance and polymorphism.
Real-World Use
An e-commerce application has Product, Cart, Order, and User classes. Each encapsulates its data and provides methods for interaction, making the codebase organized and testable.
OOP Learning Path
flowchart LR
A[Exceptions] --> B[Classes/Objects]
B --> C[Inheritance]
C --> D[Interfaces]
D --> E[Traits]
A --> F{You Are Here}
style F fill:#f90,color:#fff
Basic Class Definition
<?php
class User {
public string $name;
public string $email;
private string $password;
public function __construct(string $name, string $email, string $password) {
$this->name = $name;
$this->email = $email;
$this->password = password_hash($password, PASSWORD_DEFAULT);
}
public function verifyPassword(string $password): bool {
return password_verify($password, $this->password);
}
}
$user = new User("Alice", "alice@example.com", "secret123");
echo $user->name; // Alice
var_dump($user->verifyPassword("secret123")); // true
Properties and Methods
<?php
class Product {
public string $name;
public float $price;
private int $stock;
public function __construct(string $name, float $price, int $stock = 0) {
$this->name = $name;
$this->price = $price;
$this->stock = $stock;
}
public function isAvailable(): bool {
return $this->stock > 0;
}
public function reduceStock(int $quantity): void {
if ($quantity > $this->stock) throw new RuntimeException("Insufficient stock");
$this->stock -= $quantity;
}
}
Access Modifiers
<?php
class BankAccount {
public string $owner; // Accessible everywhere
protected float $balance; // Accessible in class and subclasses
private string $accountNumber; // Accessible only in this class
public function __construct(string $owner, float $balance, string $accountNumber) {
$this->owner = $owner;
$this->balance = $balance;
$this->accountNumber = $accountNumber;
}
public function getBalance(): float {
return $this->balance;
}
}
Static Members
<?php
class Logger {
private static array $logs = [];
public static function log(string $message): void {
self::$logs[] = "[" . date("Y-m-d H:i:s") . "] " . $message;
}
public static function getLogs(): array {
return self::$logs;
}
}
Logger::log("Application started");
Logger::log("User logged in");
print_r(Logger::getLogs());
Getters and Setters
<?php
class Temperature {
private float $celsius;
public function __construct(float $celsius) {
$this->celsius = $celsius;
}
public function getFahrenheit(): float {
return ($this->celsius * 9 / 5) + 32;
}
public function setCelsius(float $celsius): void {
if ($celsius < -273.15) throw new InvalidArgumentException("Below absolute zero");
$this->celsius = $celsius;
}
}
Common Mistakes
1. Accessing Private Properties Outside the Class
Private/protected properties cause fatal errors when accessed externally. Use getters and setters.
2. Forgetting $this
Inside class methods, use $this->property. Without $this, PHP looks for a local variable.
3. Not Using Type Declarations
PHP 8 supports typed properties. Declare types for clarity and early error detection.
4. Overusing Public Properties
Exposing all properties publicly breaks Encapsulation. Use private/protected with controlled access.
5. Constructor Property Promotion (PHP 8+)
<?php
// PHP 8 shorthand
class User {
public function __construct(
public string $name,
public string $email,
private string $password
) {}
}
Practice Questions
1. What is the difference between public, protected, and private?
public accessible everywhere. protected accessible in class and subclasses. private accessible only in the defining class.
2. What is $this?
A pseudo-variable that refers to the current object instance. Used to access properties and methods within a class.
3. How do you create a static method?
Use the static keyword: public static function method(). Call with ClassName::method().
4. What is a constructor?
A special method (__construct) that is automatically called when an object is instantiated. Used for initialization.
5. Challenge: Create a ShoppingCart class with addItem, removeItem, and getTotal methods.
<?php
class ShoppingCart {
private array $items = [];
public function addItem(string $name, float $price, int $quantity = 1): void {
$this->items[] = ["name" => $name, "price" => $price, "quantity" => $quantity];
}
public function getTotal(): float {
return array_sum(array_map(fn($i) => $i["price"] * $i["quantity"], $this->items));
}
}
$cart = new ShoppingCart();
$cart->addItem("Laptop", 999.99);
$cart->addItem("Mouse", 29.99, 2);
echo $cart->getTotal(); // 1059.97
FAQ
Mini Project: Blog Post System
Build a class-based blog post system.
<?php
class BlogPost {
public function __construct(
public string $title,
public string $content,
public string $author,
private \DateTime $createdAt = new \DateTime()
) {}
public function getExcerpt(int $length = 100): string {
return strlen($this->content) > $length
? substr($this->content, 0, $length) . "..."
: $this->content;
}
public function getFormattedDate(): string {
return $this->createdAt->format("F j, Y");
}
}
$post = new BlogPost("Hello World", "This is a blog post about PHP...", "Alice");
echo $post->getExcerpt(20);
echo $post->getFormattedDate();
What's Next
PHP Inheritance PHP Interfaces PHP Traits
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro