Updated October 6, 2023
Introduction to PHP Classes
PHP Classes is a user-defined data type encapsulating related data and functions. It defines the structure and behavior of objects that can be created based on the class. A class contains variables (properties or fields) to store data and functions (methods) to perform actions or manipulate the data.
Classes provide a way to organize and manage code, promote reusability, and improve code maintainability. They facilitate object-oriented programming (OOP) in PHP, allowing developers to create modular and extensible code.
Table of Content
- Introduction
- Class Definition in PHP
- Naming Conventions
- Properties and Methods
- Object Creation
- Constructors and Destructors
- Class Inheritance
- Abstract Classes and Interfaces
- Polymorphism and Method Overloading
- Static Properties and Methods
- Visibility and Access Control
- Class Constants
- Namespace and Autoloading
- Traits
Key Takeaways
- PHP classes define the structure and behavior of objects.
- They encapsulate data and methods within a single unit.
- Encourage code reuse to make it easier to maintain and extend.
- Objects are instances of classes, allowing for structured and modular code.
- Encourages object-oriented programming principles like inheritance and encapsulation.
Class Definition in PHP
To define a class in PHP, start with the class keyword followed by the class name. Inside the class, declare properties (variables) and methods (functions) to encapsulate data and behavior. This blueprint can then be used to create objects, each with its properties and methods.
Syntax:
class MyClass {
public $property;
public function __construct() {
// Constructor code
}
public function myMethod() {
// Method code
}
}
Naming Conventions for PHP classes
Following are some naming conventions for php classes:
Class Name
- Start with an uppercase letter.
- Use camelCase for multi-word class names (e.g., MyClass, DatabaseConnection).
File Name
- Match the class name (e.g., MyClass should be in MyClass.php).
- Use lowercase letters and underscores for file names (e.g., my_class.php).
Namespace (for PHP 5.3 and later)
- Use namespaces to organize classes into logical groups.
- Namespace names are typically lowercase and follow the directory structure (e.g., namespace MyNamespace;).
- By following these conventions, your code will be more consistent and easier to understand by other developers.
Properties and Methods of PHP Classes
Class properties (variables)
Class properties (variables) in PHP store data related to objects. They define the attributes or characteristics of objects and can have different visibility levels (public, private, protected). Properties encapsulate object states and are accessed using objects, contributing to object-oriented programming’s data abstraction and encapsulation principles.
Defining and accessing class methods (functions)
To access class properties and methods, you first need to create an instance (object) of the class. Then, you can use the object to access properties and call methods using the arrow operator (->).
$obj = new MyClass(); // Create an instance of MyClass
// Access public property
$obj->publicProperty = 'New Value';
$myValue = $obj->publicProperty;
// Call public method
$result = $obj->publicMethod();
Accessing private or protected properties/methods from outside the class is prohibited. You typically create public methods within the class to provide controlled access to these properties and methods.
Access modifiers
- public: Accessible from anywhere.
- private: Accessible only within the class that defines them.
- protected: Accessible within the class and its subclasses (inheritance).
Access modifiers help enforce encapsulation, ensuring that data and functionality are only exposed as needed and controlling how they can be accessed and manipulated within and outside the class.
Object Creation
Creating objects from PHP classes involves using the new keyword followed by the class name and optional constructor arguments.
Syntax:
<?php
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function demo() {
return "Hello, my name is {$this->name}!";
}
}
// Creating objects
$person1 = new Person("Thomas");
$person2 = new Person("Joy");
// Accessing properties and calling methods
echo $person1->name; // Output: "Thomas"
echo $person1->Demo(); // Output: "Hello, my name is Thomas!"
?>
Output:
Using new keyword to instantiate objects
Use the new keyword followed by the class name to create objects (instances) of that class.
$person1 = new Person("Thomas");
Assigning objects to variables
Store the created objects in variables for easy access and manipulation.
echo $person1->name; // Output: "Thomas"
echo $person1->Demo(); // Output: "Hello, my name is Thomas!"
Constructors and Destructors in PHP Classes
Role of constructors in initializing objects
Constructors are special methods in PHP classes that get executed automatically when an object is created from that class using the new keyword. They serve the following purposes:
- Initializing Object Properties: Constructors allow you to set initial values for object properties (variables).
- Performing Setup Tasks: You can include code within constructors to perform any setup tasks that are necessary for the object to function correctly.
For example, establishing a database connection or initializing configuration settings.
class MyClass {
public function __construct($arg1, $arg2) {
//Setup jobs or initialize properties
}
}
$obj = new MyClass($value1, $value2); // Constructor is automatically called
Destructors and their purpose in cleaning up resources
While constructors are called when an object is created, destructors are called when an object is no longer referenced or explicitly destroyed using the unset function.
Their primary purpose is to clean up resources or perform finalization tasks.
class MyClass {
public function __destruct() {
// Clean up resources
}
}
$obj = new MyClass();
unset($obj); // Destructor is automatically called when the object is unset
Class Inheritance
Class inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create new classes (child or subclass) based on existing classes (parent or superclass).
In PHP, you can achieve class inheritance using the extends keyword.
Inheriting properties and methods from parent classes
Child classes inherit properties (variables) and methods (functions) from their parent classes.
Inherited properties and methods can be accessed and used in the child class as if they were defined in the child class itself.
Example:
<?php
class Vehicle {
public $brand;
public function start() {
echo "Starting the vehicle...";
}
}
class Car extends Vehicle {
public function drive() {
echo "Driving the car...";
}
}
$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->start(); // Inherited method
$myCar->drive(); // Method specific to Car
?>
Output:
Extending classes to create subclasses
- To create a subclass, use the extends keyword followed by the parent class.
- The child class inherits all public and protected properties and methods from the parent class.
- You can add additional properties and methods to the child class or override inherited ones.
Example:
<?php
class Animal {
public function speak() {
echo "Animal speaks...";
}
}
class Dog extends Animal {
public function speak() {
echo "Dog barks...";
}
}
$dog = new Dog();
$dog->speak(); // Outputs "Dog barks..."
?>
Output:
Overriding methods in child classes
Child classes can override inherited methods by defining a new implementation in the child class with the same method name and parameters.
Example:
<?php
class Shape {
public function area() {
return 0;
}
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function area() {
return pi() * pow($this->radius, 2);
}
}
$circle = new Circle(5);
echo $circle->area(); // Outputs the area of the circle
?>
Output :
Abstract Classes and Interfaces
Creating abstract classes with unimplemented methods
Abstract classes in PHP serve as blueprints for other classes and can contain unimplemented methods (abstract methods) that must be defined in child classes.
- Define an Abstract Class: Declare an abstract class using the abstract keyword. Abstract classes cannot be instantiated directly.
- Abstract Methods: Include abstract methods within abstract classes. These methods don’t have a body but define a contract that child classes must fulfill.
Implementing interfaces to define a contract
Implementing interfaces in PHP allows you to define a contract that classes must adhere to. A contract specifies a set of methods that a class implementing the interface must provide.
Define interface:
interface Logger {
public function log($message);
public function error($message);
}
Implement the Interface: A class that wants to adhere to the contract defined by an interface must implement that interface using the implements keyword.
class FileLogger implements Logger {
public function log($message) {
// For file logging, use the log method.
file_put_contents('log.txt', $message, FILE_APPEND);
}
}
Multiple interface implementation
Multiple interface implementation in PHP allows a class to implement more than one interface, thereby inheriting multiple sets of method signatures.
class MyClass implements Interface1, Interface2, Interface3 {
// Class implementation here
}
Polymorphism and Method Overloading
Achieving polymorphism in PHP
Polymorphism is a fundamental notion in object-oriented programming that allows objects of various classes to be considered as objects of a common base class. Polymorphism in PHP is performed through method overriding and interfaces.
Here’s how it works:
Method Overriding: Child classes can override (provide their own implementation for) methods inherited from a parent class. This allows different objects to respond to the same method call differently based on their specific implementations.
Example:
<?php
class Animal {
public function speak() {
echo "Animal speaks...";
}
}
class Dog extends Animal {
public function speak() {
echo "Dog barks...";
}
}
$animal = new Dog(); // Polymorphism
$animal->speak(); // Outputs "Dog barks..."
?>
Output:
Overloading methods with varying parameters
In PHP, method overloading with varying parameters (also known as dynamic method dispatch) is not supported like in other programming languages.
PHP does not allow you to define multiple methods with the same name but different parameter lists within a single class. However, you can simulate method overloading using default argument values and conditional logic within a single method.
Example:
<?php
class MyClass {
public function exampleMethod($param1, $param2 = null, $param3 = null) {
if ($param2 !== null && $param3 !== null) {
// Handle case with all three parameters
return $param1 + $param2 + $param3;
} elseif ($param2 !== null) {
// Handle case with two parameters
return $param1 + $param2;
} else {
// Handle case with only one parameter
return $param1;
}
}
}
$obj = new MyClass();
echo $obj->exampleMethod(1); // Output: 1
echo $obj->exampleMethod(1, 2); // Output: 3
echo $obj->exampleMethod(1, 2, 3); // Output: 6
?>
Output:
The add method can accept one, two, or three arguments in this example. The conditional logic inside the method checks the number of arguments and performs the appropriate calculation.
Static Properties and Methods
Static properties and methods in PHP belong to the class itself rather than instances (objects) of the class. They are declared using the static keyword and can be accessed without creating objects.
Declaring Static Properties:
Static properties are declared within the class using the static keyword. They are shared among all class instances and can be accessed using the class name or the self keyword.
class MyClass {
public static $staticProperty = 0;
}
Accessing Static Properties:
Static properties are accessed using the class name or the self keyword:
echo MyClass::$staticProperty; // Access using the class name
echo MyClass::$staticProperty = 1; // Modify the static property
Invoking static methods without creating objects
Static methods are called on the class using the:: operator:
echo MyClass::staticMethod(); // Call the static method
Visibility and Access Control
Public:
- Access to public properties and methods is possible from anywhere inside and outside the class.
- Use public visibility when you want a property or method to be widely accessible.
- Use it for properties and methods that must be accessible from outside the class, especially when defining the class’s public interface. Public methods often represent the main entry points for using the class.
Private:
- Private properties and methods can only be accessed within the class where they are defined.
- Use private visibility to encapsulate data or functionality that should not be accessible from outside the class.
- Use it to hide internal implementation details or sensitive data from external code. Private properties are often used for encapsulating internal state, and private methods for performing helper tasks within the class.
Protected:
- Protected properties and methods can be accessed within the class where they are defined and in its subclasses (child classes) via inheritance.
- Use protected visibility to provide access to subclasses while restricting access from outside the class.
- Use it when you want to allow child classes to access certain properties or methods for customization or extension while still restricting access from external code.
Class Constants
Class constants in PHP are values associated with a class and remain constant (unchangeable) throughout the script’s execution. They are useful for defining values that should not be altered during the program’s runtime. Class constants are declared using the const keyword within a class.
Defining Constants Within a Class:
To define a class constant, use the const keyword within a class. Class constants should follow naming conventions (usually uppercase with underscores) and can be of any data type.
class MathConstants {
const PI = 3.14159265359;
const EULER = 2.71828182846;
}
Accessing class constants
You can access class constants using the scope resolution operator::, which combines the class name and constant name.
echo MathConstants::PI; // Accessing the PI constant
echo MathConstants::EULER; // Accessing the EULER constant
Namespace and Autoloading
Namespaces are a way to organize and group classes, functions, and constants in PHP to prevent naming conflicts and make your code more organized and maintainable. Namespaces allow you to create a hierarchy of classes and ensure that class names are unique.
Defining a Namespace
To define a namespace in PHP, use the namespace keyword at the beginning of your file. The namespace declaration should match the directory structure of your project.
namespace MyProject\SubNamespace;
To use classes from a namespace, you can either provide the fully qualified class name or use the use statement to alias the class name.
use MyProject\SubNamespace\MyClass;
$obj = new MyClass();
Autoloading classes
Autoloading is a mechanism that automatically includes (or “loads”) the necessary class files when you try to use a class that hasn’t been loaded yet. It simplifies code management by eliminating the need for manual ‘ require’ or ‘include’ statements for each class.
spl_autoload_register(function ($class) {
// Convert class name to a file path and include it
$file = __DIR__ . '/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) {
include_once $file;
}
});
Traits
Traits are a mechanism in PHP that allows you to reuse and share code among classes without using inheritance. They are similar to classes, but they cannot be instantiated on their own. Instead, classes use them to share methods and properties among multiple classes. Traits can achieve code reuse in PHP without creating complex inheritance hierarchies.
Purpose of Traits
The primary purposes of traits in PHP are:
- Code Reuse: Traits enable you to reuse code across multiple classes without requiring those classes to inherit from a common base class.
- To avoid issues, PHP does not support multiple inheritance, where a class can inherit from multiple classes. However, traits provide a mechanism to incorporate functionality from multiple origins into a single class.
Using Traits to Share Methods Among Classes
Within the class declaration, use the use keyword followed by the trait name to use a trait.
This brings all the methods and properties defined in the trait into the class.
Example:
trait Logging {
public function log($message) {
echo "Logging: $message";
}
}
class MyClass {
use Logging;
}
$obj = new MyClass();
$obj->log("This is a log message"); // Calls the log method from the trait
Output:
In this example, the Logging trait defines a log method, and the MyClass class uses the trait to inherit that method.
Traits are useful when you have multiple classes that must share a common set of methods but don’t necessarily have a common ancestor. However, using traits judiciously to maintain code readability and avoid excessive code duplication is essential.
Conclusion
PHP classes play a crucial role in object-oriented programming in PHP. They allow for better code organization, reusability, and maintainability. Knowing how to create and use classes to build strong and scalable PHP applications is essential. By using PHP classes effectively, developers can write efficient and well-structured code.
Recommended Articles
We hope that this EDUCBA information on “PHP Classes” was beneficial to you. You can view EDUCBA’s recommended articles for more information.