
PHP Object-Oriented Programming: Building Scalable Applications
Understanding Classes and Objects
In PHP, a class is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the objects will use. An object is an instance of a class that contains real data and behavior.
<?php
class User {
// Properties
public $name;
public $email;
// Constructor
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
// Method
public function greet() {
return "Hello, " . $this->name;
}
}
// Instantiating an object
$user = new User("Alice", "[email protected]");
// Accessing properties and methods
echo $user->greet(); // Output: Hello, AliceVisibility and Encapsulation
PHP supports three visibility levels: public, protected, and private. Proper use of visibility ensures encapsulation, which is the concept of hiding internal implementation details.
| Visibility | Accessible From | Description |
|---|---|---|
| public | anywhere | Accessible from anywhere |
| protected | class and child classes | Accessible within the class and its subclasses |
| private | class only | Accessible only within the defining class |
<?php
class BankAccount {
private $balance;
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
public function getBalance() {
return $this->balance;
}
public function deposit($amount) {
$this->balance += $amount;
}
}
$account = new BankAccount(1000);
$account->deposit(500);
echo $account->getBalance(); // Output: 1500Inheritance and Method Overriding
Inheritance allows a class (child) to inherit properties and methods from another class (parent). This promotes code reuse and helps organize related classes.
<?php
class Animal {
public function speak() {
return "This animal makes a sound.";
}
}
class Dog extends Animal {
public function speak() {
return "Woof!";
}
}
$dog = new Dog();
echo $dog->speak(); // Output: Woof!In the example above, the Dog class overrides the speak() method from the Animal class. This is known as method overriding.
Static Properties and Methods
Static members belong to the class itself rather than to any instance of the class. They are accessed using the class name and the scope resolution operator ::.
<?php
class MathUtils {
public static function add($a, $b) {
return $a + $b;
}
}
$result = MathUtils::add(3, 4);
echo $result; // Output: 7Static methods are especially useful for utility functions or when you want to track data at the class level.
Interfaces and Abstract Classes
Interfaces define a contract that classes must follow. They contain only method signatures, no implementation. Abstract classes can contain both abstract and concrete methods.
<?php
interface Logger {
public function log($message);
}
class FileLogger implements Logger {
public function log($message) {
file_put_contents('log.txt', $message . PHP_EOL, FILE_APPEND);
}
}
$logger = new FileLogger();
$logger->log("User logged in.");Abstract classes are useful when you want to share code among related classes while requiring them to implement specific methods.
<?php
abstract class Shape {
abstract public function area();
}
class Rectangle extends Shape {
public $width;
public $height;
public function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
public function area() {
return $this->width * $this->height;
}
}
$rect = new Rectangle(5, 10);
echo $rect->area(); // Output: 50Best Practices for OOP in PHP
- Use meaningful class and method names.
- Follow the Single Responsibility Principle (SRP). Each class should have one reason to change.
- Prefer composition over inheritance. Use objects as properties rather than relying on deep inheritance trees.
- Use autoloading with
spl_autoload_register()or Composer. - Leverage PHPDoc for documenting classes and methods.
