PHP, Classes and Objects
Harsh Mishra
Posted on November 29, 2024
Classes and Objects in PHP
PHP, like Java, supports object-oriented programming and uses classes and objects as its core building blocks. Understanding these concepts is essential for mastering PHP. This guide will cover everything you need to know about classes and objects in PHP.
Defining a Class
A class in PHP is a blueprint for creating objects. It defines the structure and behavior that the objects of the class will have.
Syntax
class ClassName {
// Properties (Fields)
// Methods
}
Example
class Car {
// Properties
public $color;
public $model;
public $year;
// Methods
public function displayInfo() {
echo "Model: " . $this->model . "\n";
echo "Color: " . $this->color . "\n";
echo "Year: " . $this->year . "\n";
}
}
Creating Objects
Objects are instances of classes. You create an object from a class using the new
keyword.
Syntax
$objectName = new ClassName();
Example
class Main {
public function run() {
$myCar = new Car(); // Creating an object of the Car class
$myCar->color = "Red";
$myCar->model = "Tesla";
$myCar->year = 2022;
$myCar->displayInfo();
}
}
$main = new Main();
$main->run();
Properties and Methods
Properties (also known as fields) represent the state of an object, while methods define the behavior of the object.
Properties
Properties are variables that hold the data of an object.
Example
class Car {
public $color;
public $model;
public $year;
}
Methods
Methods are functions defined within a class that describe the behaviors of the objects.
Example
class Car {
public $color;
public $model;
public $year;
public function displayInfo() {
echo "Model: " . $this->model . "\n";
echo "Color: " . $this->color . "\n";
echo "Year: " . $this->year . "\n";
}
}
Constructors
Constructors are special methods that are automatically called when an object is instantiated. They initialize the newly created object.
Default Constructor
If no constructor is defined, PHP provides a default constructor with no arguments.
Example
class Car {
public $color;
public $model;
public $year;
// Default constructor
public function __construct() {
}
public function displayInfo() {
echo "Model: " . $this->model . "\n";
echo "Color: " . $this->color . "\n";
echo "Year: " . $this->year . "\n";
}
}
Parameterized Constructor
A parameterized constructor allows you to initialize an object with specific values.
Example
class Car {
public $color;
public $model;
public $year;
// Parameterized constructor
public function __construct($color, $model, $year) {
$this->color = $color;
$this->model = $model;
$this->year = $year;
}
public function displayInfo() {
echo "Model: " . $this->model . "\n";
echo "Color: " . $this->color . "\n";
echo "Year: " . $this->year . "\n";
}
}
Using the Parameterized Constructor
class Main {
public function run() {
$myCar = new Car("Red", "Tesla", 2022);
$myCar->displayInfo();
}
}
$main = new Main();
$main->run();
Constructor Overloading
PHP does not natively support method overloading like Java, but you can simulate it using optional parameters or by handling arguments manually within a single constructor.
Example
class Car {
public $color;
public $model;
public $year;
// Simulating constructor overloading
public function __construct($color = "Unknown", $model = "Unknown", $year = 0) {
$this->color = $color;
$this->model = $model;
$this->year = $year;
}
public function displayInfo() {
echo "Model: " . $this->model . "\n";
echo "Color: " . $this->color . "\n";
echo "Year: " . $this->year . "\n";
}
}
Using the Simulated Overloaded Constructor
class Main {
public function run() {
$defaultCar = new Car();
$defaultCar->displayInfo();
$myCar = new Car("Red", "Tesla", 2022);
$myCar->displayInfo();
}
}
$main = new Main();
$main->run();
Encapsulation, Access Modifiers, and Static Members in PHP
Encapsulation
Encapsulation in PHP is the practice of bundling data (properties) and methods (functions) within a class. It ensures the internal state of an object is safe from outside interference and misuse.
Access Modifiers
Access modifiers in PHP control the visibility and accessibility of properties, methods, and constructors. PHP supports three main access modifiers:
- public: Accessible from anywhere.
- protected: Accessible within the class, subclasses, and the same package.
- private: Accessible only within the defining class.
Example Usage:
class Car {
public $color; // accessible everywhere
protected $model; // accessible within the class and subclasses
private $vin; // accessible only within the class
public function __construct($color, $model, $vin) {
$this->color = $color;
$this->model = $model;
$this->vin = $vin;
}
private function getVin() {
return $this->vin; // private method
}
public function displayInfo() {
echo "Color: $this->color\n";
echo "Model: $this->model\n";
}
}
Static Members
Static members in PHP are associated with the class itself rather than any specific instance. They can be accessed without creating an object of the class.
Static Properties:
Static properties are shared among all instances of a class. They are declared using the static
keyword.
class Car {
public static $count = 0; // static property
public function __construct() {
self::$count++;
}
}
Static Methods:
Static methods are declared using the static
keyword. They belong to the class rather than an instance.
class Car {
public static $count = 0;
public static function displayCount() {
echo "Number of cars created: " . self::$count . "\n";
}
}
Accessing Static Members:
Static members are accessed using the class name, not through an object.
class Main {
public function run() {
Car::$count = 0; // Accessing static property
Car::displayCount(); // Calling static method
}
}
$main = new Main();
$main->run();
Access Modifiers in PHP
Access modifiers in PHP control the visibility of class members, ensuring encapsulation and enforcing access restrictions.
Types of Access Modifiers
- public
- protected
- private
1. public
- Accessible from: Anywhere.
-
Usage: Use
public
for members that need to be widely accessible.
class MyClass {
public $publicVar;
public function publicMethod() {
echo "This is a public method.\n";
}
}
2. protected
- Accessible from: Within the class and its subclasses.
-
Usage: Use
protected
for members that should only be accessed within the class hierarchy.
class ParentClass {
protected $protectedVar;
protected function protectedMethod() {
echo "This is a protected method.\n";
}
}
class ChildClass extends ParentClass {
public function accessProtected() {
$this->protectedVar = 10; // Accessing protected variable
$this->protectedMethod(); // Accessing protected method
}
}
3. private
- Accessible from: Only within the class.
-
Usage: Use
private
for members that should not be accessed outside the defining class.
class MyClass {
private $privateVar;
private function privateMethod() {
echo "This is a private method.\n";
}
public function accessPrivate() {
$this->privateVar = 30; // Accessing private variable
$this->privateMethod(); // Accessing private method
}
}
Non-Access Modifiers in PHP
Non-access modifiers in PHP modify the behavior of class members without affecting their visibility.
Types of Non-Access Modifiers
- static
- final
- abstract
1. static
- Usage: Declares properties and methods that belong to the class rather than an instance.
- Example:
class MyClass {
public static $count;
public static function staticMethod() {
echo "Static method called.\n";
}
}
MyClass::$count = 10; // Accessing static property
MyClass::staticMethod(); // Calling static method
2. final
- Usage: Prevents further modification of methods or inheritance of classes.
- Variables: PHP does not support final variables.
- Methods: Final methods cannot be overridden.
- Classes: Final classes cannot be extended.
- Example:
final class MyClass {
public final function finalMethod() {
echo "Final method implementation.\n";
}
}
3. abstract
- Usage: Declares classes and methods that are incomplete and must be implemented in subclasses.
- Abstract Classes: Cannot be instantiated.
- Abstract Methods: Declared without a body and must be implemented by subclasses.
- Example:
abstract class Shape {
abstract public function draw();
}
class Circle extends Shape {
public function draw() {
echo "Drawing a circle.\n";
}
}
$circle = new Circle();
$circle->draw();
Inheritance in PHP and Access Modifiers
Inheritance
Inheritance in PHP is a mechanism where one class (subclass) can inherit the properties and methods of another class (superclass). It facilitates code reuse and allows for the creation of a hierarchical relationship between classes.
Syntax for Inheritance
class SuperClass {
// Properties and methods
}
class SubClass extends SuperClass {
// Properties and methods of SubClass
}
Example
class Animal {
public $name;
public function eat() {
echo $this->name . " is eating.\n";
}
}
class Dog extends Animal {
public function bark() {
echo $this->name . " is barking.\n";
}
}
In this example:
-
Animal
is the superclass with a property$name
and a methodeat()
. -
Dog
is the subclass that inherits$name
andeat()
fromAnimal
and adds its own methodbark()
.
Access Modifiers in Inheritance
Access modifiers in PHP determine the visibility of class members in subclasses and other parts of the program. They play a key role in inheritance.
Access Modifiers for Normal Attributes and Methods
- public: Accessible from anywhere.
- protected: Accessible within the class, subclasses, and within the same package.
- private: Accessible only within the class where it is declared.
class SuperClass {
public $publicVar;
protected $protectedVar;
private $privateVar;
public function publicMethod() {
echo "Public method in SuperClass.\n";
}
protected function protectedMethod() {
echo "Protected method in SuperClass.\n";
}
private function privateMethod() {
echo "Private method in SuperClass.\n";
}
}
class SubClass extends SuperClass {
public function accessSuperClassMembers() {
$this->publicVar = "Public"; // Accessible
$this->protectedVar = "Protected"; // Accessible
// $this->privateVar = "Private"; // Not accessible (error)
$this->publicMethod(); // Accessible
$this->protectedMethod(); // Accessible
// $this->privateMethod(); // Not accessible (error)
}
}
Access Modifiers for Static Attributes and Methods
Static members in PHP are associated with the class rather than any specific instance. They follow the same access rules as non-static members in inheritance.
class SuperClass {
public static $staticVar = "Static Variable";
public static function staticMethod() {
echo "Static method in SuperClass.\n";
}
}
class SubClass extends SuperClass {
public function accessSuperClassStaticMembers() {
echo self::$staticVar . "\n"; // Accessing static variable
self::staticMethod(); // Calling static method
}
}
Are Static Methods Inherited?
Static methods are inherited in PHP but cannot be overridden in the same sense as instance methods. When a subclass defines a static method with the same name, it hides the parent class's static method.
class SuperClass {
public static function staticMethod() {
echo "Static method in SuperClass.\n";
}
}
class SubClass extends SuperClass {
public static function staticMethod() {
echo "Static method in SubClass.\n";
}
}
SuperClass::staticMethod(); // Output: Static method in SuperClass.
SubClass::staticMethod(); // Output: Static method in SubClass.
Access Modifiers for Abstract Methods
Abstract methods in PHP must be defined in abstract classes. The visibility of an abstract method in the superclass determines its visibility in subclasses. Subclasses must implement abstract methods with the same or less restrictive access modifiers.
abstract class Shape {
abstract protected function calculateArea();
public function display() {
echo "Displaying the shape.\n";
}
}
class Circle extends Shape {
protected function calculateArea() {
echo "Calculating area of the circle.\n";
}
}
$circle = new Circle();
$circle->display();
// $circle->calculateArea(); // Error: Protected method cannot be called from outside.
Access Modifiers for Final Attributes and Methods
Final methods in PHP cannot be overridden by subclasses, and final classes cannot be extended.
- Final Methods: Prevent method overriding.
- Final Classes: Prevent inheritance.
class SuperClass {
final public function finalMethod() {
echo "This is a final method and cannot be overridden.\n";
}
}
class SubClass extends SuperClass {
// public function finalMethod() { // Error: Cannot override final method.
// }
}
final class FinalClass {
public function display() {
echo "This is a final class and cannot be extended.\n";
}
}
// class AnotherClass extends FinalClass { // Error: Cannot inherit from final class.
}
Syntax for Declaring Top-Level Classes in PHP
In PHP, the declaration of top-level classes (classes not nested inside other classes) follows a specific order of keywords. The declaration can include access modifiers, abstract or final keywords, and the class
keyword.
Keywords that can be used:
-
Access modifier:
public
-
Class type:
abstract
orfinal
Order:
[public] [abstract|final] class ClassName
Syntax:
[AccessModifier] [AbstractOrFinal] class ClassName {
// Class body
}
Important Notes:
- PHP assumes
public
as the default access modifier if none is specified. - A class cannot be both
abstract
andfinal
simultaneously. -
protected
andprivate
access modifiers are not allowed for top-level classes.
Example:
abstract class AbstractClass {
// Abstract class body
}
final class FinalClass {
// Final class body
}
Syntax for Declaring Attributes in Classes in PHP
Keywords that can be used:
-
Access modifiers:
public
,protected
,private
-
Static modifier:
static
-
Immutable modifier:
readonly
(introduced in PHP 8.1)
Order:
[AccessModifier] [static] [readonly] $attributeName
Syntax:
class ClassName {
[AccessModifier] [static] [readonly] $attributeName [= initialValue];
}
Important Notes:
- Attributes default to
public
if no access modifier is specified. -
static
attributes belong to the class rather than instances. -
readonly
attributes can only be initialized once, either during declaration or in the constructor (PHP 8.1+).
Example:
class MyClass {
public static readonly int $id = 42; // PHP 8.1+
private string $name;
protected bool $isActive = true;
}
Syntax for Declaring Methods in Classes in PHP
Keywords that can be used:
-
Access modifiers:
public
,protected
,private
-
Static modifier:
static
-
Final modifier:
final
-
Abstract modifier:
abstract
Order:
[AccessModifier] [static] [final|abstract] function methodName(parameters): returnType
Syntax:
class ClassName {
[AccessModifier] [static] [final|abstract] function methodName(paramType $paramName): returnType {
// Method body
}
}
Important Notes:
- If no access modifier is specified, the method is
public
by default. -
static
methods belong to the class, not instances. -
final
methods cannot be overridden in subclasses. -
abstract
methods must be declared in an abstract class and cannot have a body.
Example:
abstract class AbstractClass {
abstract protected function calculateArea(): float;
public final function getName(): string {
return "AbstractClass";
}
}
class ConcreteClass extends AbstractClass {
protected function calculateArea(): float {
return 42.0;
}
}
Abstract Classes in PHP
Abstract classes in PHP are similar to their counterparts in Java, used to define a blueprint for other classes. They contain both abstract methods (methods without implementation) and concrete methods (methods with implementation). Abstract classes are declared using the abstract
keyword and cannot be instantiated directly.
1. Introduction to Abstract Classes
An abstract class serves as a base class for derived classes. It defines common behaviors for its subclasses while allowing the implementation of specific methods in those subclasses.
2. Declaring an Abstract Class
To declare an abstract class in PHP, use the abstract
keyword before the class
keyword.
Example:
abstract class Animal {
abstract public function makeSound(); // Abstract method
public function sleep() { // Concrete method
echo "Sleeping...\n";
}
}
3. Abstract Methods
Abstract methods are defined in the abstract class but do not have a body. Subclasses must implement all abstract methods.
Example:
abstract class Animal {
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
echo "Bark\n";
}
}
4. Concrete Methods
Concrete methods in an abstract class have a body and can be inherited by the subclasses as-is or overridden.
Example:
abstract class Animal {
public function eat() {
echo "Eating...\n";
}
}
class Cat extends Animal {
public function eat() {
echo "The cat is eating...\n";
}
}
5. Creating Subclasses
Subclasses of an abstract class must implement all its abstract methods unless the subclass is also declared as abstract.
Example:
abstract class Animal {
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
echo "Bark\n";
}
}
class Cat extends Animal {
public function makeSound() {
echo "Meow\n";
}
}
6. Instantiating Abstract Classes
Abstract classes cannot be instantiated directly. You must use a concrete subclass to create an instance.
Example:
abstract class Animal {
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
echo "Bark\n";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Bark
7. Constructors in Abstract Classes
Abstract classes can have constructors, and their constructors are called when a subclass is instantiated.
Example:
abstract class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
echo "$this->name says: Bark\n";
}
}
$dog = new Dog("Rex");
$dog->makeSound(); // Output: Rex says: Bark
8. Abstract Classes with Fields and Methods
Abstract classes can include instance variables and concrete methods, providing reusable functionality for subclasses.
Example:
abstract class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function makeSound();
public function sleep() {
echo "$this->name is sleeping...\n";
}
}
class Cat extends Animal {
public function makeSound() {
echo "$this->name says: Meow\n";
}
}
$cat = new Cat("Whiskers");
$cat->makeSound(); // Output: Whiskers says: Meow
$cat->sleep(); // Output: Whiskers is sleeping...
9. Static Methods in Abstract Classes
Abstract classes can contain static methods. Static methods belong to the class and can be called without instantiating it.
Example:
abstract class Animal {
abstract public function makeSound();
public static function info() {
echo "Animals are living organisms.\n";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Bark\n";
}
}
Animal::info(); // Output: Animals are living organisms.
Syntax for Declaring Abstract Classes in PHP
Keywords that can be used:
abstract
-
public
,protected
,private
(access modifiers)
Order:
abstract class ClassName [extends SuperClass] {
// Class body
}
Examples:
Abstract Class with Abstract and Concrete Methods
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
abstract public function calculateArea();
public function getColor() {
return $this->color;
}
}
class Circle extends Shape {
private $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius ** 2;
}
}
$circle = new Circle("red", 5);
echo "The area of the circle is: " . $circle->calculateArea() . "\n";
echo "The circle color is: " . $circle->getColor() . "\n";
Abstract Class with Fields and Final Methods
abstract class Vehicle {
protected $brand;
public function __construct($brand) {
$this->brand = $brand;
}
abstract public function start();
public final function stop() {
echo "The vehicle has stopped.\n";
}
}
class Car extends Vehicle {
public function start() {
echo "$this->brand car is starting...\n";
}
}
$car = new Car("Toyota");
$car->start(); // Output: Toyota car is starting...
$car->stop(); // Output: The vehicle has stopped.
Important Notes:
- Abstract classes cannot be instantiated directly.
- Abstract methods must be implemented by non-abstract subclasses.
- Subclasses that do not implement all abstract methods must also be declared abstract.
- Concrete methods in abstract classes are optional for subclasses to override.
- Abstract classes can have constructors, properties, and constants.
- Abstract classes can use any visibility modifiers for their methods and properties.
Interfaces in PHP
An interface in PHP defines a contract for classes that implement it. It specifies the methods a class must implement, but does not provide any method implementations itself. Interfaces allow for more flexible and modular code, enabling classes to adhere to a common set of method signatures, regardless of their inheritance hierarchy.
1. Introduction to Interfaces
An interface in PHP is similar to an abstract class, but it can only define method signatures without any implementation. A class that implements an interface must provide the implementations for all methods declared in the interface. A class can implement multiple interfaces, making interfaces a key part of PHP's support for multiple inheritance of behavior.
2. Declaring an Interface
To declare an interface, use the interface
keyword. Interfaces can only contain method declarations (no method bodies), constants, and abstract methods.
Example:
interface Animal {
public function makeSound(); // Method declaration
public function sleep(); // Method declaration
}
3. Implementing an Interface
A class that implements an interface must provide implementations for all the methods declared in the interface. A class can implement multiple interfaces, separating them with commas.
Example:
interface Animal {
public function makeSound(); // Method declaration
public function sleep(); // Method declaration
}
class Dog implements Animal {
public function makeSound() {
echo "Bark\n";
}
public function sleep() {
echo "Dog is sleeping...\n";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Bark
$dog->sleep(); // Output: Dog is sleeping...
4. Interface Method Signatures
Methods in interfaces cannot have a body, and they must be public. When a class implements an interface, it must implement these methods exactly as declared in the interface, including the method signature.
Example:
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius ** 2;
}
}
$circle = new Circle(5);
echo "Area of the circle: " . $circle->calculateArea(); // Output: Area of the circle: 78.539816339745
5. Multiple Interface Implementation
A class in PHP can implement multiple interfaces. This allows for more flexibility in designing systems where classes can adhere to different contracts.
Example:
interface Animal {
public function makeSound();
}
interface Movable {
public function move();
}
class Dog implements Animal, Movable {
public function makeSound() {
echo "Bark\n";
}
public function move() {
echo "Dog is moving...\n";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Bark
$dog->move(); // Output: Dog is moving...
6. Interface Constants
Interfaces can contain constants. These constants are automatically public and can be accessed by any class that implements the interface.
Example:
interface Animal {
const SOUND = "Generic animal sound";
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
echo self::SOUND . "\n"; // Accessing constant from the interface
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Generic animal sound
7. Interface Inheritance
An interface can extend another interface. This means that the child interface inherits all methods (signatures) from the parent interface, and can also add new methods. A class implementing the child interface must implement all methods from both the parent and child interfaces.
Example:
interface Animal {
public function makeSound();
}
interface Movable {
public function move();
}
interface WalkingAnimal extends Animal, Movable {
public function walk();
}
class Dog implements WalkingAnimal {
public function makeSound() {
echo "Bark\n";
}
public function move() {
echo "Dog is moving...\n";
}
public function walk() {
echo "Dog is walking...\n";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Bark
$dog->move(); // Output: Dog is moving...
$dog->walk(); // Output: Dog is walking...
8. Static Methods in Interfaces
Interfaces cannot contain static methods. All methods declared in an interface must be instance methods. Static methods are not allowed in interfaces, as interfaces define instance-level contracts for the implementing classes.
Syntax for Declaring and Implementing Interfaces in PHP
Keywords that can be used:
interface
public
Order:
interface InterfaceName {
public function methodName();
}
class ClassName implements InterfaceName {
public function methodName() {
// Method implementation
}
}
Examples:
Interface with Method Signatures
interface Shape {
public function calculateArea();
public function calculatePerimeter();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius ** 2;
}
public function calculatePerimeter() {
return 2 * pi() * $this->radius;
}
}
$circle = new Circle(5);
echo "Area of the circle: " . $circle->calculateArea() . "\n";
echo "Perimeter of the circle: " . $circle->calculatePerimeter() . "\n";
Interface with Multiple Implementations
interface Animal {
public function makeSound();
}
interface Movable {
public function move();
}
class Dog implements Animal, Movable {
public function makeSound() {
echo "Bark\n";
}
public function move() {
echo "Dog is moving...\n";
}
}
class Bird implements Animal, Movable {
public function makeSound() {
echo "Chirp\n";
}
public function move() {
echo "Bird is flying...\n";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: Bark
$dog->move(); // Output: Dog is moving...
$bird = new Bird();
$bird->makeSound(); // Output: Chirp
$bird->move(); // Output: Bird is flying...
Important Notes:
- Interface Methods: Methods in an interface must be public and cannot have a body.
- Implementing Multiple Interfaces: A class can implement multiple interfaces, separating them with commas.
-
Access Modifiers: All methods in an interface are implicitly public. Access modifiers like
private
orprotected
are not allowed. - Interface Constants: Interfaces can declare constants that are automatically public and can be accessed by implementing classes.
- Interface Inheritance: An interface can extend one or more interfaces, combining their method signatures.
- Static Methods: Interfaces cannot contain static methods.
- Implementing All Methods: A class must implement all methods defined by the interfaces it implements.
Posted on November 29, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.