0% found this document useful (0 votes)
80 views

OOP and Exception Handling

This document discusses object-oriented programming (OOP) and exception handling in PHP. It defines OOP and compares it to procedural programming. It describes classes and objects as the main aspects of OOP. It provides examples of defining a class, creating objects, using the $this keyword, constructors, access modifiers, inheritance, namespaces, and throwing and catching exceptions.

Uploaded by

Mustafa Waqar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views

OOP and Exception Handling

This document discusses object-oriented programming (OOP) and exception handling in PHP. It defines OOP and compares it to procedural programming. It describes classes and objects as the main aspects of OOP. It provides examples of defining a class, creating objects, using the $this keyword, constructors, access modifiers, inheritance, namespaces, and throwing and catching exceptions.

Uploaded by

Mustafa Waqar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

OOP and Exception Handling

in PHP
Khalilullah Akbari
+93 729908855
[email protected]
PHP OOP
Definition
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform
operations on the data, while object-oriented programming is about creating objects
that contain both data and functions.

Object-oriented programming has several advantages over procedural programming:


OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP makes it possible to create full reusable applications
Classes and Objects
Classes and objects are the two main aspects of object-oriented
programming.

Example:
There is a class of Car, and its objects are Volvo, Toyota, Audi, …
Define a Class
A class is defined by using the class keyword, followed by the name of the class and a
pair of curly braces ({}). All its properties and methods go inside the braces:

Syntax
<?php
class Fruit {
// code goes here...
}
?>
Example
<?php
class Fruit { // Making objects
// Properties
public $name; $apple = new Fruit();
public $color; $banana = new Fruit();
$apple->set_name('Apple');
// Methods $banana->set_name('Banana');
function set_name($name) {
$this->name = $name; echo $apple->get_name();
} echo "<br>";
function get_name() { echo $banana->get_name();
return $this->name;
} ?>
}
The $this Keyword
The $this keyword refers to the current object, and is only available inside methods.

<?php
Example: class Fruit {
public $name;
function set_name($nameofuser) {
$this->name = $nameofuser;
}
}
$apple = new Fruit();
$apple->set_name("Apple");

echo $apple->name;
?>
Constructor
<?php
class Fruit {
A constructor allows you to initialize an public $name;
object's properties upon creation of the public $color;
object.
function __construct($name) {
$this->name = $name;
If you create a __construct() function, PHP }
will automatically call this function when you function get_name() {
return $this->name;
create an object from a class. }
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>
Access Modifiers
Properties and methods can have access modifiers which control where they can be
accessed.
There are three access modifiers:
•public - the property or method can be accessed from everywhere. This is default.
•protected - the property or method can be accessed within the class and by
classes derived from that class.
•private - the property or method can ONLY be accessed within the class.
Access Modifiers

<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
Inheritance
PHP inheritance in OOP = When a class derives from another class.

The child class will inherit all the public and protected properties and methods from
the parent class. In addition, it can have its own properties and methods.

An inherited class is defined by using the extends keyword.


Inheritance
<?php // Strawberry is inherited from Fruit
class Fruit { class Strawberry extends Fruit {
public $name; public function message() {
public $color; echo "Am I a fruit or a berry? ";
public function __construct($name, $color) }
{ }
$this->name = $name; $strawberry
$this->color = $color; = new Strawberry("Strawberry", "red");
} $strawberry->message();
public function intro() { $strawberry->intro();
echo "The fruit is {$this->name} and the ?>
color is {$this->color}.";
}
}
PHP Namespaces
Namespaces are qualifiers that solve two different problems:

❑ They allow for better organization by grouping classes that work together to
perform a task
❑ They allow the same name to be used for more than one class.
Declaring a Namespace
Namespaces are declared at the beginning of a file using the namespace keyword.

Syntax
Declare a namespace called Html:
namespace Html;

A namespace declaration must be the first thing in the PHP file


Declaring a Namespace
<?php
namespace Html; <!DOCTYPE html>
class Table { <html>
public $title = ""; <body>
public $numRows = 0;
public function message() { <?php
echo "<p>Table '{$this->title}' has {$this- $table->message();
>numRows} rows.</p>"; ?>
}
} </body>
$table = new Table(); </html>
$table->title = "My table";
$table->numRows = 5;
?>
Using Namespaces
Any code that follows a namespace declaration is operating inside the namespace, so
classes that belong to the namespace can be instantiated without any qualifiers.

$table = new Html\Table()


$row = new Html\Row();
PHP Exceptions
PHP Exceptions
An exception is an object that describes an error or unexpected
behavior of a PHP script.
Exceptions are thrown by many PHP functions and classes.
User defined functions and classes can also throw exceptions.
Exceptions are a good way to stop a function when it comes across
data that it cannot use.
Throwing an Exception
The throw statement allows a user
defined function or method to throw <?php
an exception. When an exception is function divide($dividend, $divisor) {
if($divisor == 0) {
thrown, the code following it will not throw new Exception("Division by zero");
be executed. }
return $dividend / $divisor;
}

echo divide(5, 0);


?>
The try...catch Statement
To avoid the error from the example above, we can use the try...catch statement to
catch exceptions and continue the process.

Syntax:
try {
//code that can throw exceptions
} catch(Exception $e) {
//code that runs when an exception is caught
}
Example
<?php
function divide($dividend, $divisor) {
if($divisor == 0) {
throw new Exception("Division by zero");
}
return $dividend / $divisor;
}
try {
echo divide(5, 0);
} catch(Exception $e) {
echo "Unable to divide.";
}
?>
Methods
Method Description
getMessage() Returns a string describing why the exception was thrown

getPrevious() If this exception was triggered by another one, this method returns the previous
exception. If not, then it returns null

getCode() Returns the exception code

getFile() Returns the full path of the file in which the exception was thrown

getLine() Returns the line number of the line of code which threw the exception
Example
try {
echo divide(5, 0);
} catch(Exception $ex) {
<?php
$code = $ex->getCode();
function divide($dividend, $divisor) {
$message = $ex->getMessage();
if($divisor == 0) {
$file = $ex->getFile();
throw new Exception("Division by
$line = $ex->getLine();
zero", 1);
echo "Exception thrown in $file on line
}
$line: [Code $code]
return $dividend / $divisor;
$message";
}
}
?>
Thank You

You might also like