PHP OOP: Classes, Methods, Inheritance
PHP OOP: Classes, Methods, Inheritance
A class is a blueprint that defines the structure and behavior of a specific type of object. It specifies the properties
(data) and methods (functions) that an object of this type should have. In PHP, you define a class using
the class keyword, followed by the name of the class.
Creating a Class in PHP
To create a class in PHP, you need to follow these steps:
A property is a variable that belongs to an object, while a method is a function that belongs to an object. You can
define properties and methods within a class by specifying their visibility (public, private, or protected) followed by
their name.
Once you've defined a class, you can create objects (instances) of that class using the new keyword. Each object will
have its own set of properties and methods, as defined by the class.
By understanding how to access and manipulate the data and behavior of objects, you'll be able to create more
sophisticated and flexible applications.
Accessing Object Properties
To access an object's properties, you use the arrow operator (->) followed by the property name. Keep in mind
that you can only access properties that have a visibility of public.
Here's an example of how to set and access the properties of a Car object:
To call an object's method, you use the arrow operator (->) followed by the method name and a pair of
parentheses. As with properties, you can only call methods that have a visibility of public.
Here's an example of how to call the startEngine() and stopEngine() methods of a Car object:
$myCar = new Car();
$myCar->startEngine();
// Code that uses the car while the engine is running
$myCar->stopEngine();
Inside a class, you can use the $this keyword to refer to the current object. This is useful when you need to access
or modify the object's properties or call its methods from within the class.
These special methods are used to initialize and clean up objects, ensuring that your application runs efficiently and
smoothly.
Constructors
A constructor is a special method that gets called automatically when you create a new object. It's useful for
initializing the object's properties or performing other setup tasks. In PHP, constructors are defined using
the __construct() method.
Now, when you create a new Car object, you can pass the make, model, and year values as arguments to the
constructor:
$myCar = new Car('Toyota', 'Camry', 2022);
echo "Make: " . $myCar->make . "\n";
echo "Model: " . $myCar->model . "\n";
echo "Year: " . $myCar->year . "\n";
Destructors
A destructor is another special method that gets called automatically when an object is destroyed or when the script
ends. It's useful for cleaning up resources or performing other tasks before the object is removed from memory. In
PHP, destructors are defined using the __destruct() method.
Concept of inheritance in PHP, which allows you to create new classes based on existing ones. This powerful feature
promotes code reusability and modularity, making your applications more organized and easier to maintain.
What is Inheritance?
Inheritance is an Object-Oriented Programming concept that allows you to create a new class (the subclass or
derived class) by extending an existing class (the superclass or base class). The subclass inherits properties and
methods from the superclass, and you can add or override them as needed.
Extending Classes in PHP
To create a subclass in PHP, you use the extends keyword followed by the name of the superclass. The subclass
will inherit all the public and protected properties and methods from the superclass.
Now, a Truck object will have all the properties and methods of a Car object, as well as the
additional payloadCapacity property and loadCargo() and unloadCargo() methods.
Overriding Methods
In some cases, you might want the subclass to have a different implementation of a method that it inherits from the
superclass. You can achieve this by overriding the method in the subclass.
With this new implementation, when you call the startEngine() method on a Truck object, the custom code for
starting the engine in a truck will be executed instead of the code from the Car class.
Visibility in PHP classes, which determines the accessibility of properties and methods. Understanding visibility is
crucial for creating well-structured and secure code, as it allows you to control how your objects can be interacted
with.
Public Visibility
Public properties and methods can be accessed from anywhere, including outside the class and by its subclasses.
To declare a public property or method, you use the public keyword.
Private properties and methods can only be accessed from within the class that defines them. They cannot be accessed
from outside the class or by its subclasses. To declare a private property or method, you use the private keyword.
Protected Visibility
Protected properties and methods can be accessed from within the class that defines them and from its subclasses,
but not from outside the class. To declare a protected property or method, you use the protected keyword.
By using visibility, you can control how your objects are accessed and manipulated, ensuring that they are used
correctly and securely. For example, you might use private properties and methods to store sensitive data or
implement critical functionality that should not be exposed to external code.
A static property is a property that belongs to the class, not to individual objects. To declare a static property, you
use the static keyword along with the visibility keyword (public, private, or protected).
To access a static property, you use the scope resolution operator (::) followed by the property name. You do not
need to create an object to access a static property.
A static method is a method that belongs to the class, not to individual objects. To declare a static method, you use
the static keyword along with the visibility keyword (public, private, or protected).
To call a static method, you use the scope resolution operator (::) followed by the method name. You do not need
to create an object to call a static method.
Static properties and methods can be useful in situations where you need to maintain data or functionality that is
shared across all instances of a class, such as counting the number of objects created or providing utility functions.
However, static members should be used judiciously, as they can make your code less flexible and harder to test. In
general, you should favor instance properties and methods over static members when possible.
Polymorphism allows objects of different classes to be treated as objects of a common superclass, enabling you to
write more flexible and reusable code. Interfaces define a contract that classes must adhere to, ensuring consistent
implementation across different classes.
What is Polymorphism?
Polymorphism is an Object-Oriented Programming concept that enables you to use objects of different classes
interchangeably, as long as they share a common superclass or implement a common interface. This allows you to
write more flexible code that can work with various object types.
Interfaces in PHP
An interface is a contract that defines a set of methods that implementing classes must have. Interfaces allow you
to define common behavior across different classes, ensuring that they have a consistent implementation.
To declare an interface in PHP, you use the interface keyword followed by the interface name. Interfaces can
include method signatures but cannot include properties or method implementations.
To implement an interface in a class, you use the implements keyword followed by the interface name. The class
must then provide implementations for all methods defined in the interface.
Now, any class that implements the Drivable interface can be treated as a drivable object, regardless of its specific
class.
Using Polymorphism with Interfaces
Polymorphism allows you to treat objects of different classes that implement the same interface as if they were
objects of a common type. This enables you to write more flexible and reusable code.
performRoadTest($car);
performRoadTest($truck);
This method will have the same name for all its uses, but might produce different output in different situations.
Method overloading is a key concept under the umbrella of polymorphism.
Traditional Overloading
For example, say you have an add method that you want to use to sum a couple of numbers in these ways:
function add(int $a, int $b): int
{
return $a + $b;
}
function add(int $a, int $b, int $c): int
{
$sum = $a + $b + $c;
return $sum > 10 ? 10 : $sum;
}
In the first definition, the method takes in two parameters and simply returns their sum. In the second definition, it
takes three parameters and it returns the sum of these only when it's equal to 10 or less.
Now, unlike other programming languages, PHP doesn't really let you redefine a method multiple times like this:
You would get an error like this: PHP Fatal error: Cannot redeclare SampleClass::add(). But PHP supports
method overloading using a magic keyword, __call.
Using this magic method, you can create as many methods and as many variations of each of these methods as you
like.
For example, to achieve our intended goal with the add function, update the __call definition and
your SampleClass to be like this:
class SampleClass
{
function __call($function_name, $arguments)
{
$count = count($arguments);
Use the count method to know how many arguments are passed to your method.
Check the function name being passed in. This __call will house all the different methods you intend to create
variations of, so the name should be unique and be used to group variations of the methods.
Handle the logic as you like based on the different number of arguments. Here, we return the sum as is when we
have two arguments. We return the sum if it's less than 10 when we have three arguments.
When you call the add method, PHP checks for a method with the same name in the class, if it doesn't find it, it
calls the __call method instead, and that is how the code is run.
To call the add method now, create a new instance of the SampleClass class and try it out.
$sampleObject = new SampleClass;
echo $sampleObject->add(12, 12) . PHP_EOL; // Outputs 24
echo $sampleObject->add(12, 2, 6) . PHP_EOL; // Outputs 10
Example method overloading
<?php
class Shape {
const PI = 3.142 ;
function __call($name,$arg){
if($name == 'area')
switch(count($arg)){
case 0 : return 0 ;
case 1 : return self::PI * $arg[0] ;
case 2 : return $arg[0] * $arg[1];
}
class MyClass
{
public static function __callStatic($name, $arguments)
{
if ($name === 'foo') {
if (count($arguments) === 1) {
echo "Called static foo with one argument: {$arguments[0]}\n";
} elseif (count($arguments) === 2) {
echo "Called static foo with two arguments: {$arguments[0]} and
{$arguments[1]}\n";
} else {
echo "Invalid number of arguments for static foo method\n";
}
} else {
echo "Static method $name not found\n";
}
}
}
Encapsulation is the process of hiding the implementation details of an object and providing a public interface for
interacting with the object. Encapsulation is important because it allows you to control access to an object's properties
and methods, which helps to prevent unintended modifications and ensures that the object behaves as expected.
You can encapsulate an object's properties in PHP by declaring them private or protected. Private properties can only
be accessed from within the object's class, while protected properties can be accessed from within the object's class
and its subclasses.
In this example, we define an Employee class with three private properties (name, age, and salary) and three public
methods (getName, getAge, and getSalary). The private properties can only be accessed from within the Employee
class, while the public methods provide a public interface for interacting with the object.
Magic Methods:
List and explain some of the commonly used magic methods in PHP.
Demonstrate the use of the __construct and __destruct magic methods.
How does overloading work with magic methods in PHP?
Error Handling:
Discuss the role of exceptions in PHP and how they are handled.
Provide an example of custom exception handling in an object-oriented PHP application.
index.php
Employee.php
create.php
read.php
update.php
<div class="container">
<h3>Add Employee Details</h3>
<form method="post" name="form1" >
<table class="table-condensed" width="25%" border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="number" name="age"></td>
</tr>
<tr>
<td>Salary</td>
<td><input type="number" name="salary"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Save" class="
btn btn-info"></td>
</tr>
</table>
</form>
</div>
<?php
include_once("classes/Employee.php");
$emp = new Employee();
$inserted = 0;
if(isset($_POST['Submit'])) {
$name = $emp->escapeString($_POST['name']);
$age = $emp->escapeString($_POST['age']);
$salary = $emp->escapeString($_POST['salary']);
$emptyInput = $emp->check_empty($_POST, array('name', 'age', 'salary'));
if(!$emptyInput) {
$array = array(
"employee_name" => $name,
"employee_age" => $age,
"employee_salary" => $salary
);
$emp->insert('employee',$array); // Table name, column names and respectiv
e values
$inserted = $emp->getResult();
}
}
?>
<div class="container">
<h3>Edit Employee Details</h3>
<form name="form1" method="post">
<table class="table-condensed" width="25%" border="0">
<tr>
Then we will display employee details in edit form to edit employee details.
<?php
include_once("classes/Employee.php");
$emp = new Employee();
$id = $emp->escapeString($_GET['id']);
$emp->get('employee', '*', NULL, "id='$id'");
$result = $emp->getResult();
foreach ($result as $res) {
$name = $res['employee_name'];
$age = $res['employee_age'];
$salary = $res['employee_salary'];
}
Then on employee update form submit, we will handle functionality to update employee details using method $emp-
>update().
<?php
if(isset($_POST['update'])) {
$id = $emp->escapeString($_POST['id']);
$name = $emp->escapeString($_POST['name']);
$age = $emp->escapeString($_POST['age']);
$salary = $emp->escapeString($_POST['salary']);
$emptyInput = $emp->check_empty($_POST, array('name', 'age', 'salary'));
if(!$emptyInput) {
$array = array(
"employee_name" => $name,
"employee_age" => $age,
"employee_salary" => $salary
);
$emp->update('employee',$array,"id='$id'");
if($emp->getResult()){
header("Location: index.php");
}
}
}
?>
<?php
include_once("classes/Employee.php");
$emp = new Employee();
$id = $emp->escapeString($_GET['id']);
$emp->delete('employee',"id='$id'");
if($emp->getResult()) {
header("Location:index.php");
}
What’s an Exception?
An exception is an unwanted or unexpected event that occurs during the execution of a program. It disrupts the
normal flow of instructions and can be caused by a variety of errors. In PHP, an exception is represented by the
class Exception.
The Exception class in PHP is the base class for all exceptions in the language. It provides methods for getting
information about the exception, such as the file and line number where it occurred, and a message describing the
error.
When an exception is thrown, it can be caught by a block of code with proper instructions to handle it. If an exception
isn’t caught, it will be handled by the default exception handler, which usually results in a fatal error and the
termination of the script.
try {
// code that may throw an exception
$file = fopen('nonexistent.txt', 'r');
} catch (Exception $e) {
// code to handle the exception
echo 'An error occurred: ' . $e->getMessage();
}
In this example, the code inside the try block attempts to open a file that doesn’t exist. This throws an exception,
which is caught by the catch block. The catch block then prints out an error message. If we weren’t using the try-
catch block in this example and the exception were thrown, the script would be terminated and the error message
would be displayed. This would result in the script not being able to continue execution. Using the try-catch block
allows the script to handle the exception gracefully and continue executing if desired.
To throw an exception, we can use the throw keyword. The throw keyword is used inside the try block to throw an
exception when a certain condition is met. The exception can be of type Exception, or a custom exception class we
create. Here’s an example:
In this example, the divide function is expected to take two parameters, $a and $b, and return the result of
dividing $a by $b. However, if the second parameter is zero, an exception is thrown.
Additionally, by creating a custom exception class, we can catch specific types of exceptions and handle them
differently, depending on the specific problem that occurs. To create a custom exception class, we can define a new
class and extend Exception like this:
Then, later on, we can use this class as a type of throw exception:
Here’s an example of how we can add a customErrorMessage() method to the custom exception class:
In this example, we’ve added a method called customErrorMessage to the DivideByZeroException class. This
method uses the getLine(), getFile(), and getMessage() methods of the Exception class to build a custom error
message.
We can use this custom method in the catch block like this:
try {
echo divide(5, 0);
} catch (DivideByZeroException $e) {
echo $e->customErrorMessage();
}
The getLine() method returns the line number where the exception is thrown and the getFile() method returns the
file name where the exception is thrown, which allows us to have a more informative error message. With
this customErrorMessage method, the output will be something like “Error on line (line number) in file (file name):
Cannot divide by zero”, and it will give more detailed information in case we need to debug the exception.
This way, we can add custom functionality, or throw different types of exceptions to be handled in different ways.
In PHP, you can handle multiple exceptions by using multiple catch blocks. Each catch block handles a specific type
of exception. When an exception is thrown, the catch blocks are checked in order, and the first one that can handle
the thrown exception is executed.
Here is an example:
try {
// Code that may throw exceptions
} catch (MyException $e) {
// Handle MyException
} catch (Exception $e) {
// Handle other exceptions
}
The getMessage method in PHP exception handling is used to get a string representation of the exception message.
This method is defined in the Exception class and can be called on any object of a class that extends Exception.
The exception message is usually set when the exception is thrown, like this: throw new Exception(“Error
message”).
set_exception_handler('myExceptionHandler');
Usually, when we want to use a class or function that’s defined in another file, we have to require or include them:
<?php
require 'lib/classes/GreeterService.php'; # We must explicitly specify the paths
require 'lib/classes/DateService.php';
However, manually requiring files like this becomes tedious and unmaintainable when our project grows. Suppose
you decide to move the GreeterService.php file to some other location, you’d then have to update all
the require statements.
spl_autoload_register to the rescue
Fortunately, PHP gives us the spl_autoload_register function to make life easier. spl_autoload_register has the
following signature:
spl_autoload_register(
callable $autoload_function = ?,
bool $throw = true,
bool $prepend = false
): bool
For now, let’s focus on the first argument – the autoload_function. Using spl_autoload_register , we can replace
the previous code with the require statements to something like this:
<?php
if (is_readable($filePath)) {
require $filePath;
}
}
$greeter = new GreeterService();
$greeter->greet('Jimmy');
$date = new DateService();
$date->printDate();