Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
27 views32 pages

PHP OOP: Classes, Methods, Inheritance

Uploaded by

bhupalbarbote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views32 pages

PHP OOP: Classes, Methods, Inheritance

Uploaded by

bhupalbarbote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Object-Oriented Programming in PHP!

 Introduction to Object-Oriented Programming (OOP) in PHP


 Defining and Creating Classes
 Working with Object Properties and Methods
 Constructors and Destructors
 Inheritance: Extending Classes and Overriding Methods
 Visibility: Public, Private, and Protected Properties and Methods
 Static Properties and Methods
 Polymorphism and Interfaces in PHP
Defining and Creating Classes
What is a Class?

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:

 Use the class keyword to declare the class.


 Choose a descriptive name for the class, following the naming conventions (PascalCase).
 Enclose the class definition within curly braces {}.

Here's an example of a simple class definition:


class Car {
// Properties and methods go here
}
Defining Properties and Methods

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.

Here's an example of a class with properties and methods:


class Car {
public $make;
public $model;
public $year;

Compiled By: Basanta Chapagain Object Oriented PHP


public function startEngine() {
// Code to start the engine
}

public function stopEngine() {


// Code to stop the engine
}
}
Creating Objects

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.

Here's an example of creating an object from the Car class:


$myCar = new Car();
Working with Object Properties and Methods

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:

$myCar = new Car();


$myCar->make = 'Toyota';
$myCar->model = 'Camry';
$myCar->year = 2022;

echo "Make: " . $myCar->make . "\n";


echo "Model: " . $myCar->model . "\n";
echo "Year: " . $myCar->year . "\n";

Compiled By: Basanta Chapagain Object Oriented PHP


Accessing Object Methods

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();

The $this Keyword

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.

Here's an example of using the $this keyword within a class method:


class Car {
public $speed = 0;

public function accelerate() {


$this->speed += 5;
echo "Current speed: " . $this->speed . " km/h\n";
}
}

Constructors and Destructors

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.

Compiled By: Basanta Chapagain Object Oriented PHP


Here's an example of a constructor in the Car class:
class Car {
public $make;
public $model;
public $year;

public function __construct($make, $model, $year) {


$this->make = $make;
$this->model = $model;
$this->year = $year;
}
}

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.

Here's an example of a destructor in the Car class:


class Car {
// Properties and constructor go here

public function __destruct() {


echo "The " . $this->make . " " . $this->model . " object has been
destroyed.\n";
}
}

Compiled By: Basanta Chapagain Object Oriented PHP


When the Car object is destroyed, the destructor will be called, and you'll see the message:

The Toyota Camry object has been destroyed.

Inheritance: Extending Classes and Overriding Methods

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.

Here's an example of a Truck class that extends the Car class:


class Truck extends Car {
public $payloadCapacity;
public function loadCargo($weight) {
// Code to load cargo
}
public function unloadCargo() {
// Code to unload cargo
}
}

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.

Compiled By: Basanta Chapagain Object Oriented PHP


To override a method, you simply define it in the subclass with the same name and signature as in the superclass.
Here's an example of overriding the startEngine() method in the Truck class:
class Truck extends Car {
// Properties and other methods go here

public function startEngine() {


// Custom code for starting the engine in a truck
}
}

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: Public, Private, and Protected Properties and Methods

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.

Here's an example of public properties and methods in a Car class:


class Car {
public $make;
public $model;
public $year;

public function startEngine() {


// Code to start the engine
}
}

Compiled By: Basanta Chapagain Object Oriented PHP


Private Visibility

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.

Here's an example of private properties and methods in a Car class:


class Car {
private $make;
private $model;
private $year;

private function startEngine() {


// Code to start the engine
}
}

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.

Here's an example of protected properties and methods in a Car class:


class Car {
protected $make;
protected $model;
protected $year;

protected function startEngine() {


// Code to start the engine
}
}

Compiled By: Basanta Chapagain Object Oriented PHP


Why Use Visibility?

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.

Static Properties and Methods


Static Properties

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).

Here's an example of a static property in a Car class:


class Car {
public static $numberOfCars = 0;
}

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.

Here's an example of accessing the numberOfCars static property:


echo "Number of cars: " . Car::$numberOfCars . "\n";
Static Methods

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).

Here's an example of a static method in a Car class:


class Car {
public static function honk() {
echo "Honk! Honk!\n";
}
}

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.

Compiled By: Basanta Chapagain Object Oriented PHP


Here's an example of calling the honk() static method:
Car::honk();
When to Use Static Members

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 and Interfaces

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.

Here's an example of an interface declaration:


interface Drivable {
public function startEngine();
public function stopEngine();
public function accelerate();
public function brake();
}

Compiled By: Basanta Chapagain Object Oriented PHP


Implementing Interfaces

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.

Here's an example of a Car class implementing the Drivable interface:

class Car implements Drivable {


// Properties go here

public function startEngine() {


// Code to start the engine
}

public function stopEngine() {


// Code to stop the engine
}

public function accelerate() {


// Code to accelerate
}

public function brake() {


// Code to brake
}
}

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.

Here's an example of using polymorphism with the Drivable interface:

Compiled By: Basanta Chapagain Object Oriented PHP


function performRoadTest(Drivable $vehicle) {
$vehicle->startEngine();
$vehicle->accelerate();
$vehicle->brake();
$vehicle->stopEngine();
}

$car = new Car();


$truck = new Truck(); // Assuming Truck also implements Drivable

performRoadTest($car);
performRoadTest($truck);

What is Method Overloading?


Method overloading is a concept that allows you to have a method that can perform differently based on its number
of parameters. It allows you have multiple definitions for a same method in the same class.

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:

Compiled By: Basanta Chapagain Object Oriented PHP


class SampleClass
{
function add(int $a, int $b): int
{
return $a + $b;
}
function add(int $a, int $b, int $c): int
{
return $a + $b + $c > 10 ?? 10;
}
}

You would get an error like this: PHP Fatal error: Cannot redeclare SampleClass::add(). But PHP supports
method overloading using a magic keyword, __call.

The __call keyword


This is a magic method that PHP calls when it tries to execute a method of a class and it doesn't find it. This magic
keyword takes in two arguments: a function name and other arguments to be passed into the function. Its definition
looks like this:

function __call(string $function_name, array $arguments) {}

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);

// Check function name


if ($function_name == 'add') {

Compiled By: Basanta Chapagain Object Oriented PHP


if ($count == 2) {
return array_sum($arguments);
} else if ($count == 3) {
return array_sum($arguments) > 10 ? 10 :
array_sum($arguments);
}
}
}
}
The code is pretty self explanatory. Here's a step by step breakdown:

 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];
}

Compiled By: Basanta Chapagain Object Oriented PHP


}
}
$circle = new Shape();
echo $circle->area(3);
$rect = new Shape();
echo $rect->area(8,6);
?>
__callStatic() for Static Method Overloading:

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";
}
}
}

MyClass::foo('arg1'); // Called static foo with one argument: arg1


MyClass::foo('arg1', 'arg2'); // Called static foo with two arguments: arg1
and arg2
MyClass::bar(); // Static method bar not found

Compiled By: Basanta Chapagain Object Oriented PHP


Encapsulation in PHP

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.

Here's an example of encapsulation in PHP:


class Employee {
private $name;
private $age;
private $salary;
public function __construct($name, $age, $salary) {
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
public function getSalary() {
return $this->salary;
}
}
$employee = new Employee("Rajnish Shrestha", 30, 50000);
echo $employee->getName() . " is " . $employee->getAge() . " years old and earns $"
. $employee->getSalary() . " per year.";

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.

Compiled By: Basanta Chapagain Object Oriented PHP


Questions for Object Oriented PHP
Basic Concepts:
 Explain the fundamental principles of object-oriented programming.
 Differentiate between a class and an object in PHP.
 What is encapsulation, and how is it implemented in PHP?
 Describe the significance of inheritance in OOP.

Classes and Objects:


 Create a class in PHP for a simple entity (e.g., a car, a person) with properties and methods.
 Demonstrate how to instantiate an object from a class.
 How are constructors and destructors used in PHP classes?
 Explain the concept of method overloading and method overriding.

Inheritance and Polymorphism:


 Provide an example of a class hierarchy using inheritance.
 Illustrate polymorphism in PHP with practical code examples.
 Discuss the importance of the parent keyword in inheritance.
 Explain the concept of abstract classes and interfaces.

Visibility and Access Modifiers:


 Describe the purpose of access modifiers (public, private, protected) in PHP.
 Give examples of when to use each access modifier.
 Discuss the differences between self and parent keywords.

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.

Object Oriented CRUD Operation with PHP and MySQL


To create CRUD operation with PHP and MySQL using Object Oriented Programming (OOP) technique, so the file
structure for this example is following.

 index.php
 Employee.php
 create.php
 read.php
 update.php

Compiled By: Basanta Chapagain Object Oriented PHP


 delete.php
Steps1: Create MySQL Database Table
As in this example, we will perform CRUD operation on employee data, so first we will create employee MySQL
database table to perform operations. So we will use below query to create table.

CREATE TABLE `employee` (


`id` int(11) NOT NULL COMMENT 'primary key',
`employee_name` varchar(255) NOT NULL COMMENT 'employee name',
`employee_salary` double NOT NULL COMMENT 'employee salary',
`employee_age` int(11) NOT NULL COMMENT 'employee age'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table';

Steps2: Create Employee Class with CRUD Method


Now we will create class Employee to handle connection to MySQL database and CRUD operations like select,
insert, update and delete with MySQL database. We will have method get() to select employee records,
method insert() to insert employee record, method update() to update employee details and method delete() to delete
employee records. Here is complete Employee class with all method, you just need to change MySQL database
connection details when run on your server.
<?php
class Employee {
private $databaseHost = "localhost";
private $databaseUser = "root";
private $databasePass = "";
private $databaseName = "phpzag_demos";
private $connection = false;
private $result = array();
private $myQuery = "";
private $numResults = "";
public function __construct() {
self::connect();
}
private function connect(){
if(!$this->connection){
$connected = @mysql_connect($this->databaseHost,$this->databaseUser
,$this->databasePass);
@mysql_set_charset('utf8', $connected);
if($connected){
$seldb = @mysql_select_db($this->databaseName,$connected);

Compiled By: Basanta Chapagain Object Oriented PHP


if($seldb){
$this->connection = true;
return true;
}else{
array_push($this->result,mysql_error());
return false;
}
}else{
array_push($this->result,mysql_error());
return false;
}
}else{
return true;
}
}
public function get($table, $rows = '*', $join = null, $where = null, $order = null,
$limit = null){
$selectQuery = 'SELECT '.$rows.' FROM '.$table;
if($join != null){
$selectQuery .= ' JOIN '.$join;
}
if($where != null){
$selectQuery .= ' WHERE '.$where;
}
if($order != null){
$selectQuery .= ' ORDER BY '.$order;
}
if($limit != null){
$selectQuery .= ' LIMIT '.$limit;
}
$this->myQuery = $selectQuery;
if($this->checkTable($table)){
$query = @mysql_query($selectQuery);
if($query){

Compiled By: Basanta Chapagain Object Oriented PHP


$this->numResults = mysql_num_rows($query);
for($row = 0; $row < $this->numResults; $row++){
$result = mysql_fetch_array($query);
$keys = array_keys($result);
for($key = 0; $key < count($keys); $key++){
if(!is_int($keys[$key])){
if(mysql_num_rows($query) >= 1){
$this->result[$row][$keys[$key]] = $result[$keys[$
key]];
}else{
$this->result = null;
}
}
}
}
return true;
}else{
array_push($this->result,mysql_error());
return false;
}
}else{
return false;
}
}
public function insert($table,$params=array()){
if($this->checkTable($table)){
$sqlQuery='INSERT INTO `'.$table.'` (`'.implode('`, `',array_keys($params))
.'`) VALUES ("' . implode('", "', $params) . '")';
$this->myQuery = $sqlQuery;
if($ins = @mysql_query($sqlQuery)){
array_push($this->result,mysql_insert_id());
return true;
}else{
array_push($this->result,mysql_error());

Compiled By: Basanta Chapagain Object Oriented PHP


return false;
}
} else {
return false;
}
}
public function update($table,$params=array(),$where){
if($this->checkTable($table)){
$args=array();
foreach($params as $field=>$value){
$args[]=$field.'="'.$value.'"';
}
$sqlQuery='UPDATE '.$table.' SET '.implode(',',$args).' WHERE '.$wh
ere;
$this->myQuery = $sqlQuery;
if($query = @mysql_query($sqlQuery)){
array_push($this->result,mysql_affected_rows());
return true;
}else{
array_push($this->result,mysql_error());
return false;
}
}else{
return false;
}
}
public function delete($table,$where = null){
if($this->checkTable($table)){
if($where == null){
$deleteQuery = 'DROP TABLE '.$table;
}else{
$deleteQuery = 'DELETE FROM '.$table.' WHERE '.$where;
}
if($del = @mysql_query($deleteQuery)){

Compiled By: Basanta Chapagain Object Oriented PHP


array_push($this->result,mysql_affected_rows());
$this->myQuery = $deleteQuery;
return true;
}else{
array_push($this->result,mysql_error());
return false;
}
}else{
return false;
}
}
private function checkTable($table){
$tableExist = @mysql_query('SHOW TABLES FROM '.$this->databaseName.' LIKE "
'.$table.'"');
if($tableExist){
if(mysql_num_rows($tableExist)==1){
return true;
}else{
array_push($this->result,$table." does not exist in this database");
return false;
}
}
}
public function getResult(){
$value = $this->result;
$this->result = array();
return $value;
}
public function escapeString($data){
return mysql_real_escape_string($data);
}
public function check_empty($data, $fields) {
$msg = null;
foreach ($fields as $value) {

Compiled By: Basanta Chapagain Object Oriented PHP


if (empty($data[$value])) {
$msg .= "$value field empty";
}
}
return $msg;
}
}

Steps3: Handle Employee Insert Functionality


Now we will handle Employee insert functionality into MySQL Database table. For this, we will design a
employee details HTML Form in create.php file.

<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>

Compiled By: Basanta Chapagain Object Oriented PHP


Then we will handle functionality to insert Employee records into MySQL database table Employee. So we will
include class Employee.php and then create Employee object. Then on form submit, we will create array of
employee details and call Employee method $emp->insert(’employee’,$array); to insert employee details
into Employee table.

<?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();
}
}
?>

Steps4: Handle Employee Select Functionality


Now we will display employee records from MySQL database in read.php. We will include
class Employee.php and create object and then call method $emp->get(); to get employee records.
<?php
include_once("classes/Employee.php");
$emp = new Employee();
$emp->get('employee', '*', NULL, "", 'id DESC LIMIT 50');
$result = $emp->getResult();
?>

Then we will display employee records in HTML table.

Compiled By: Basanta Chapagain Object Oriented PHP


<table class="table table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Salary</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
foreach ($result as $key => $res) {
echo "<tr>";
echo "<td>".$res['employee_name']."</td>";
echo "<td>".$res['employee_age']."</td>";
echo "<td>".$res['employee_salary']."</td>";
echo "<td><a href=\"update.php?id=$res[id]\" class=\"btn btn-info\"
role=\"button\">Edit</a> <a
href=\"delete.php?id=$res[id]\"
onClick=\"return confirm('Are you sure you want to delete?')\"
class=\"btn btn-info\"
role=\"button\">Delete</a></td>";
}
?>
</tbody>
</table>

Steps5: Handle Employee Update Functionality


Now we will handle functionality to update employee in file update.php. first we will create employee edit HTML
Form.

<div class="container">
<h3>Edit Employee Details</h3>
<form name="form1" method="post">
<table class="table-condensed" width="25%" border="0">
<tr>

Compiled By: Basanta Chapagain Object Oriented PHP


<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name;
?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age;?>
"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="salary" value="<?php echo $sal
ary;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['
id'];?>></td>
<td><input type="submit" name="update" value="Update" class
="btn btn-info"></td>
</tr>
</table>
</form>
</div>

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'];
}

Compiled By: Basanta Chapagain Object Oriented PHP


?>

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");
}
}
}
?>

Steps3: Handle Employee Delete Functionality


Now finally we will handle employee delete functionality in delete.php by calling Employee method $emp-
>delete().

<?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");
}

Compiled By: Basanta Chapagain Object Oriented 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.

Basic Usage of Exception


The basic syntax for handling exceptions in PHP is the try-catch block. The try block contains the code that may
throw an exception, and the catch block contains the code that will handle the exception. If an exception is thrown
inside the try block, the script will jump to the corresponding catch block.
Here’s an example:

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.

The throw Keyword

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:

function divide($a, $b) {


if ($b == 0) {
throw new Exception('Cannot divide by zero');
}

Compiled By: Basanta Chapagain Object Oriented PHP


return $a / $b;
}
try {
echo divide(5, 0);
} catch (Exception $e) {
echo 'An error occurred: ' . $e->getMessage();
}

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.

Creating a Custom Exception


It’s also possible to create a custom exception class by extending the built-in Exception class. Creating a custom
exception class allows us to handle specific types of exceptions in a more tailored and organized way. By extending
the built-in Exception class, we can create our own exception class that inherits all the properties and methods of
the Exception class, but also allows us to add our own properties and methods that are specific to the type of
exception we’re trying to handle. This allows us to have more control over how our exceptions are handled, and can
make our code more readable and maintainable.

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:

class DivideByZeroException extends Exception {}

Then, later on, we can use this class as a type of throw exception:

function divide($a, $b) {


if ($b == 0) {
throw new DivideByZeroException('Cannot divide by zero');
}
return $a / $b;
}
try {
echo divide(5, 0);
} catch (DivideByZeroException $e) {
echo 'An error occurred: ' . $e->getMessage();
}

Here’s an example of how we can add a customErrorMessage() method to the custom exception class:

class DivideByZeroException extends Exception {

Compiled By: Basanta Chapagain Object Oriented PHP


public function customErrorMessage() {
$message = "Error on line " . $this->getLine() . " in file " . $this->getFil
e() . ": " . $this->getMessage();
return $message;
}
}

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.

What is the difference between Error and Exception in PHP?


In PHP, both errors and exceptions are used to handle different types of problematic situations in a program. An
error is a serious problem that prevents the program from continuing to run. It is usually caused by a code issue or a
system problem. On the other hand, an exception is a condition that changes the normal flow of the program
execution. It is typically used for handling expected but potentially problematic situations, like invalid input or file
not found. Unlike errors, exceptions can be caught and handled within the program using try-catch blocks.

How can I create a custom exception in PHP?


In PHP, you can create a custom exception by extending the built-in Exception class. You can add custom properties
and methods to your exception class to provide more specific information about the exceptional condition.
Here is an example:

class MyException extends Exception {


// Custom properties and methods
}
You can then throw and catch your custom exception just like a standard exception.

Compiled By: Basanta Chapagain Object Oriented PHP


How can I handle multiple exceptions in PHP?

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
}

What is the purpose of the finally block in PHP exception handling?


The finally block in PHP exception handling is used to specify code that should be executed regardless of whether
an exception was thrown or not. This is useful for cleanup code that should always be run, like closing a file or a
database connection. The finally block is optional and is added after the catch blocks.
How can I rethrow an exception in PHP?
In PHP, you can rethrow an exception by using the throw statement inside a catch block. This is useful when you
want to handle an exception partially and let it propagate to a higher level for further handling. Here is an example:
try {
// Code that may throw an exception
} catch (Exception $e) {
// Partially handle the exception
throw $e; // Rethrow the exception
}

What is the use of the getMessage method in PHP exception handling?

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”).

How can I catch all exceptions in PHP?


In PHP, you can catch all exceptions by using a catch block with the Exception class. This will catch any exception
that is an instance of the Exception class or a subclass of it.
Here is an example:
try {
// Code that may throw exceptions
} catch (Exception $e) {
// Handle all exceptions
}

Compiled By: Basanta Chapagain Object Oriented PHP


How can I handle exceptions globally in PHP?
In PHP, you can handle exceptions globally by setting a custom exception handler function with the
set_exception_handler function. This function will be called whenever an exception is thrown and not caught.
Here is an example:
function myExceptionHandler($exception) {
// Handle the exception
}

set_exception_handler('myExceptionHandler');

Understanding spl_autoload_register and PHP’s autoloading mechanism

The trouble with require

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';

$greeter = new GreeterService();


$greeter->greet('Jimmy');

$date = new DateService();


$date->printDate();
?>

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

Compiled By: Basanta Chapagain Object Oriented PHP


spl_autoload_register('classLoader');
function classLoader(string $className)
{
$filePath = __DIR__ . "/lib/classes/$className.php";

if (is_readable($filePath)) {
require $filePath;
}
}
$greeter = new GreeterService();
$greeter->greet('Jimmy');
$date = new DateService();
$date->printDate();

Compiled By: Basanta Chapagain Object Oriented PHP

You might also like