SlideShare a Scribd company logo
USING FUNCTIONS IN PHP
Functions in PHP are blocks of code designed to perform specific
tasks.
They enhance code reusability, maintainability, and
organization.
PHP supports two main types of functions: built-in functions
and user-defined functions.
 PHP comes with a vast library of built-in functions, which are
pre-defined and ready to use. These functions cover a wide range
of tasks, including string manipulation, mathematical
calculations, and file handling.
Examples
 strlen(): Returns the length of a string.
 array_push(): Adds one or more elements to the end of an array.
 var_dump(): Displays structured information about one or more
variables.
Built-in Functions
USER-DEFINED FUNCTIONS
User-defined functions allow you to create your own functions tailored to
your specific needs.
function
functionName($parameter1,
$parameter2) {
// code to be executed
}
function sample($name) {
echo "Hello, $name!";
}
// Calling the function
sample("Abc");
Syntax Example
FUNCTION PARAMETERS
Functions can accept parameters, which are variables passed into the
function. You can define multiple parameters, separated by commas.
function add($a, $b)
{
return $a + $b;
}
$result = add(5, 10);
echo "The sum is: $result"; // Outputs: The sum is: 15
DEFAULT PARAMETER VALUES
You can set default values for parameters. If a value is not
provided during the function call, the default value will be used.
function greet($name = "Guest")
{
echo "Hello, $name!";
}
greet(); // Outputs: Hello, Guest!
greet("Bob"); // Outputs: Hello, Bob!
RETURNING VALUES
Functions can return values using the return statement. Once a return
statement is executed, the function stops executing.
function square($number)
{
return $number * $number;
}
echo "The square of 4 is: " . square(4); // Outputs: The square of 4 is: 16
CALL BY VALUE VS. CALL BY REFERENCE
By default, PHP passes arguments to functions by value, meaning a copy of the variable is
passed. If you want to pass a variable by reference (allowing the function to modify the
original variable), you can use the & symbol.
function increment(&$value)
{
$value++;
}
$num = 5;
increment($num);
echo $num; // Outputs: 6
UNIT - IV
PHP and Operating System
Managing Files USING FTP in PHP
Steps to manage files via FTP in
PHP
 Connect to an FTP Server
 Upload a File
 Download a File
 Delete a File
 List Files in a Directory
 Change Directory
 Create a Directory
 Close the FTP Connection
<?php
$ftp_server = "ftp.example.com";
$ftp_username = "your_username";
$ftp_password = "your_password";
$local_file = "localfile.txt";
$remote_file = "remotefile.txt";
// Establish FTP connection
$ftp_conn = ftp_connect($ftp_server) or
die("Could not connect to $ftp_server");
// Login to FTP server
if (@ftp_login($ftp_conn, $ftp_username,
$ftp_password)) {
echo "Connected to $ftp_server
successfully.n";
// Upload a file
if (ftp_put($ftp_conn, $remote_file,
$local_file, FTP_BINARY))
{
echo "Successfully uploaded
$local_file.n";
} else {
echo "Error uploading
$local_file.n";
}
// List files in root directory
$file_list = ftp_nlist($ftp_conn, "/");
if ($file_list) {
echo "Files in root directory:n";
foreach ($file_list as $file) {
echo "$filen";
}
}
// Close connection
ftp_close($ftp_conn);
} else {
echo "Could not log in to
$ftp_server.";
}
?>
Reading and Writing Files
in PHP
Writing to a
File
 To write to a file in PHP, you
can use the fwrite( ) function,
which writes content to an
open file.
 To open a file, use the fopen( )
function.
<?php
$filename = "example.txt";
$content = "Hello, this is a sample text.";
// Open the file for writing (creates the file if it
doesn't exist)
$file = fopen($filename, "w");
// Write content to the file
if (fwrite($file, $content)) {
echo "File written successfully.";
} else {
echo "Error writing to the file.";
}
// Close the file
fclose($file);
?>
File Modes
•"w": Write-only. Opens and clears the file content (if the file exists) or
creates a new file.
•"w+": Read and write. Clears the file content or creates a new one.
•"a": Write-only. Opens and writes to the end of the file (append mode).
•"a+": Read and write. Writes to the end of the file.
•"r": Read-only. Opens the file for reading. Fails if the file does not exist.
•"r+": Read and write. Does not clear the file content.
Reading from a File
 To read content from a
file, you can use the
fread() function,
 For smaller files,
file_get_contents() can be
used, which reads the
entire file into a string.
Reading with
file_get_contents()
<?php
$filename = "example.txt";
// Read entire file content
$content =
file_get_contents($filename);
if ($content !== false) {
echo "File content:n$content";
} else {
echo "Error reading the file.";
}
?>
Steps to Read a File Using
fread()
<?php
$filename = "example.txt";
// Open the file for reading
$file = fopen($filename, "r");
// Read file content
if ($file) {
$filesize = filesize($filename);
$content = fread($file, $filesize);
echo "File content:n$content";
} else {
echo "Error opening the file.";
}
// Close the file
fclose($file);
?>
 fopen() Opens a file.
 fwrite() Writes data to a file.
 fread() Reads data from a file.
 file_get_contents() Reads entire file
content.
 fgets() Reads a line from a
file.
 file_exists() Checks if a file exists.
 unlink() Deletes a file.
 chmod() Changes file
permissions.
 move_uploaded_file() Handles file uploads
Common PHP File
Functions
DEVELOPING OBJECT-ORIENTED SCRIPT USING PHP
create reusable and modular code by organizing it into
objects. Let's go over the basic structure for creating an
object-oriented script in PHP.
 Classes: Blueprint for creating objects. Classes define
properties (variables) and methods (functions) that can
be used by the objects created from the class.
 Objects: Instances of a class.
 Properties: Variables within a class.
 Methods: Functions defined inside a class that can
<?php
// Define a class
class Car {
// Properties
public $make;
public $model;
public $year;
// Constructor (automatically called when an object is created)
public function __construct($make, $model, $year) {
$this->make = $make;
$this->model = $model;
$this->year = $year;
}
// Method
public function getCarInfo() {
return "Car: " . $this->make . " " . $this->model . " (" . $this->year .
")";
}
// Setter method
public function setYear($year)
{
$this->year = $year;
}
// Getter method
public function getYear() {
return $this->year;
}
}
// Create an object (instance of the Car class)
$myCar = new Car("Toyota", "Corolla", 2020);
// Accessing a method
echo $myCar->getCarInfo();
//Output: Car: Toyota Corolla (2020)
// Changing the year using a setter method
$myCar->setYear(2022);
// Accessing the updated value
echo $myCar->getCarInfo();
?>
Output: Car: Toyota Corolla (2022)
($make, $model, and $year) and methods (getCarInfo, setYear,
getYear).
 Constructor: The __construct() method initializes an object
when it is created. Here, it sets the car’s make, model, and year.
Methods
 getCarInfo() is a method that returns a string with the car’s
details.
 setYear() and getYear() are setter and getter methods to
update and retrieve the value of the year property.
 Object Instantiation: $myCar = new Car("Toyota", "Corolla",
2020); creates a new object of the Car class, passing initial
values.
 Accessing Methods and Properties: $myCar->getCarInfo();
accesses the object’s method, and $myCar->setYear(2022);
EXCEPTION HANDLING
 Exception handling is a mechanism in programming that allows a system to handle unexpected events or errors that
occur during the execution of a program.
 These unexpected events, known as exceptions, can disrupt the normal flow of an application.
 Exception handling provides a controlled way to respond to these exceptions, allowing the program to either correct
the issue or gracefully terminate.
Why Do We Need Exception Handling?
1.Maintaining Application Flow: Without exception handling, an unexpected error could
terminate the program abruptly. Exception handling ensures that the program can continue
running or terminate gracefully.
2.Informative Feedback: When an exception occurs, it provides valuable information about the
problem, helping developers to debug and users to understand the issue.
3.Resource Management: Exception handling can ensure that resources like database
connections or open files are closed properly even if an error occurs.
4.Enhanced Control: It allows developers to specify how the program should respond to specific
types of errors.
Here is an example of a basic PHP try catch statement.
try {
// run your code here
}
catch (exception $e) {
//code to handle the exception
}
finally {
//optional code that always runs
}
PHP error handling keywords
The following keywords are used for PHP exception handling.
 Try: The try block contains the code that may potentially throw an exception. All of the code
within the try block is executed until an exception is potentially thrown.
 Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP
runtime will then try to find a catch statement to handle the exception.
 Catch: This block of code will be called only if an exception occurs within the try code block. The
code within your catch statement must handle the exception that was thrown.
 Finally: In PHP 5.5, the finally statement is introduced. The finally block may also be specified
after or instead of catch blocks.
 Code within the finally block will always be executed after the try and catch blocks, regardless of
whether an exception has been thrown, and before normal execution resumes. This is useful for
scenarios like closing a database connection regardless if an exception occurred or not.
PHP try catch with multiple exception types
try {
// run your code here
}
catch (Exception $e) {
echo $e->getMessage();
}
catch (InvalidArgumentException $e)
{
echo $e->getMessage();
}
When to use try catch-finally
Example for try catch-finally:
try {
print "this is our try block n";
throw new Exception();
} catch (Exception $e) {
echo "something went wrong, caught yah! n";
} finally {
print "this part is always executed n";
}

More Related Content

Similar to object oriented programming in PHP & Functions (20)

PPT
Php Tutorial
SHARANBAJWA
 
PPT
Php mysql
Alebachew Zewdu
 
PPT
phpwebdev.ppt
rawaccess
 
PDF
Php Tutorials for Beginners
Vineet Kumar Saini
 
PDF
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
PPTX
Introduction in php part 2
Bozhidar Boshnakov
 
PPT
slidesharenew1
truptitasol
 
PPT
My cool new Slideshow!
omprakash_bagrao_prdxn
 
PPTX
php programming.pptx
rani marri
 
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
PDF
Wt unit 4 server side technology-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PDF
PHP Unit-1 Introduction to PHP
Lariya Minhaz
 
PPT
PHP
sometech
 
PPT
Phpwebdevelping
mohamed ashraf
 
PPTX
php part 2
Shagufta shaheen
 
PDF
How to Write the Perfect PHP Script for Your Web Development Class
Emma Jacob
 
PPT
Phpwebdev
Luv'k Verma
 
PDF
basic concept of php(Gunikhan sonowal)
Guni Sonow
 
Php Tutorial
SHARANBAJWA
 
Php mysql
Alebachew Zewdu
 
phpwebdev.ppt
rawaccess
 
Php Tutorials for Beginners
Vineet Kumar Saini
 
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
Introduction in php part 2
Bozhidar Boshnakov
 
slidesharenew1
truptitasol
 
My cool new Slideshow!
omprakash_bagrao_prdxn
 
php programming.pptx
rani marri
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Wt unit 4 server side technology-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PHP Unit-1 Introduction to PHP
Lariya Minhaz
 
Phpwebdevelping
mohamed ashraf
 
php part 2
Shagufta shaheen
 
How to Write the Perfect PHP Script for Your Web Development Class
Emma Jacob
 
Phpwebdev
Luv'k Verma
 
basic concept of php(Gunikhan sonowal)
Guni Sonow
 

More from BackiyalakshmiVenkat (10)

PPT
DBMS-Unit-3.0 Functional dependencies.ppt
BackiyalakshmiVenkat
 
PPT
Functional Dependencies in rdbms with examples
BackiyalakshmiVenkat
 
PPTX
database models in database management systems
BackiyalakshmiVenkat
 
PPTX
Normalization in rdbms types and examples
BackiyalakshmiVenkat
 
PPTX
introduction to advanced operating systems
BackiyalakshmiVenkat
 
PPT
Introduction to Database Management Systems
BackiyalakshmiVenkat
 
PPTX
Linked list, Singly link list and its operations
BackiyalakshmiVenkat
 
PPTX
Linked Lists, Single Linked list and its operations
BackiyalakshmiVenkat
 
PPTX
Evlotion of Big Data in Big data vs traditional Business
BackiyalakshmiVenkat
 
PPTX
AN ANALYSIS OF THE REASONS FOR NON-PERFORMING ASSETS (NPAs) TO THE STATE BANK...
BackiyalakshmiVenkat
 
DBMS-Unit-3.0 Functional dependencies.ppt
BackiyalakshmiVenkat
 
Functional Dependencies in rdbms with examples
BackiyalakshmiVenkat
 
database models in database management systems
BackiyalakshmiVenkat
 
Normalization in rdbms types and examples
BackiyalakshmiVenkat
 
introduction to advanced operating systems
BackiyalakshmiVenkat
 
Introduction to Database Management Systems
BackiyalakshmiVenkat
 
Linked list, Singly link list and its operations
BackiyalakshmiVenkat
 
Linked Lists, Single Linked list and its operations
BackiyalakshmiVenkat
 
Evlotion of Big Data in Big data vs traditional Business
BackiyalakshmiVenkat
 
AN ANALYSIS OF THE REASONS FOR NON-PERFORMING ASSETS (NPAs) TO THE STATE BANK...
BackiyalakshmiVenkat
 
Ad

Recently uploaded (20)

PPT
digestive system for Pharm d I year HAP
rekhapositivity
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PPTX
Blanket Order in Odoo 17 Purchase App - Odoo Slides
Celine George
 
PPTX
national medicinal plants board mpharm.pptx
SHAHEEN SHABBIR
 
PPTX
Folding Off Hours in Gantt View in Odoo 18.2
Celine George
 
PPTX
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
PDF
Exploring-the-Investigative-World-of-Science.pdf/8th class curiosity/1st chap...
Sandeep Swamy
 
PPTX
How to Consolidate Subscription Billing in Odoo 18 Sales
Celine George
 
PPTX
ANORECTAL MALFORMATIONS: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PDF
Right to Information.pdf by Sapna Maurya XI D
Directorate of Education Delhi
 
PDF
Ziehl-Neelsen Stain: Principle, Procedu.
PRASHANT YADAV
 
PPTX
PPT on the Development of Education in the Victorian England
Beena E S
 
PDF
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
PPTX
How to Define Translation to Custom Module And Add a new language in Odoo 18
Celine George
 
PDF
Comprehensive Guide to Writing Effective Literature Reviews for Academic Publ...
AJAYI SAMUEL
 
PPTX
Presentation: Climate Citizenship Digital Education
Karl Donert
 
PPTX
Nutrition Month 2025 TARP.pptx presentation
FairyLouHernandezMej
 
PPTX
ENGLISH LEARNING ACTIVITY SHE W5Q1.pptxY
CHERIEANNAPRILSULIT1
 
PPTX
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
PDF
FULL DOCUMENT: Read the full Deloitte and Touche audit report on the National...
Kweku Zurek
 
digestive system for Pharm d I year HAP
rekhapositivity
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
Blanket Order in Odoo 17 Purchase App - Odoo Slides
Celine George
 
national medicinal plants board mpharm.pptx
SHAHEEN SHABBIR
 
Folding Off Hours in Gantt View in Odoo 18.2
Celine George
 
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
Exploring-the-Investigative-World-of-Science.pdf/8th class curiosity/1st chap...
Sandeep Swamy
 
How to Consolidate Subscription Billing in Odoo 18 Sales
Celine George
 
ANORECTAL MALFORMATIONS: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Right to Information.pdf by Sapna Maurya XI D
Directorate of Education Delhi
 
Ziehl-Neelsen Stain: Principle, Procedu.
PRASHANT YADAV
 
PPT on the Development of Education in the Victorian England
Beena E S
 
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
How to Define Translation to Custom Module And Add a new language in Odoo 18
Celine George
 
Comprehensive Guide to Writing Effective Literature Reviews for Academic Publ...
AJAYI SAMUEL
 
Presentation: Climate Citizenship Digital Education
Karl Donert
 
Nutrition Month 2025 TARP.pptx presentation
FairyLouHernandezMej
 
ENGLISH LEARNING ACTIVITY SHE W5Q1.pptxY
CHERIEANNAPRILSULIT1
 
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
FULL DOCUMENT: Read the full Deloitte and Touche audit report on the National...
Kweku Zurek
 
Ad

object oriented programming in PHP & Functions

  • 1. USING FUNCTIONS IN PHP Functions in PHP are blocks of code designed to perform specific tasks. They enhance code reusability, maintainability, and organization. PHP supports two main types of functions: built-in functions and user-defined functions.
  • 2.  PHP comes with a vast library of built-in functions, which are pre-defined and ready to use. These functions cover a wide range of tasks, including string manipulation, mathematical calculations, and file handling. Examples  strlen(): Returns the length of a string.  array_push(): Adds one or more elements to the end of an array.  var_dump(): Displays structured information about one or more variables. Built-in Functions
  • 3. USER-DEFINED FUNCTIONS User-defined functions allow you to create your own functions tailored to your specific needs. function functionName($parameter1, $parameter2) { // code to be executed } function sample($name) { echo "Hello, $name!"; } // Calling the function sample("Abc"); Syntax Example
  • 4. FUNCTION PARAMETERS Functions can accept parameters, which are variables passed into the function. You can define multiple parameters, separated by commas. function add($a, $b) { return $a + $b; } $result = add(5, 10); echo "The sum is: $result"; // Outputs: The sum is: 15
  • 5. DEFAULT PARAMETER VALUES You can set default values for parameters. If a value is not provided during the function call, the default value will be used. function greet($name = "Guest") { echo "Hello, $name!"; } greet(); // Outputs: Hello, Guest! greet("Bob"); // Outputs: Hello, Bob!
  • 6. RETURNING VALUES Functions can return values using the return statement. Once a return statement is executed, the function stops executing. function square($number) { return $number * $number; } echo "The square of 4 is: " . square(4); // Outputs: The square of 4 is: 16
  • 7. CALL BY VALUE VS. CALL BY REFERENCE By default, PHP passes arguments to functions by value, meaning a copy of the variable is passed. If you want to pass a variable by reference (allowing the function to modify the original variable), you can use the & symbol. function increment(&$value) { $value++; } $num = 5; increment($num); echo $num; // Outputs: 6
  • 8. UNIT - IV PHP and Operating System Managing Files USING FTP in PHP Steps to manage files via FTP in PHP  Connect to an FTP Server  Upload a File  Download a File  Delete a File  List Files in a Directory  Change Directory  Create a Directory  Close the FTP Connection
  • 9. <?php $ftp_server = "ftp.example.com"; $ftp_username = "your_username"; $ftp_password = "your_password"; $local_file = "localfile.txt"; $remote_file = "remotefile.txt"; // Establish FTP connection $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server"); // Login to FTP server if (@ftp_login($ftp_conn, $ftp_username, $ftp_password)) { echo "Connected to $ftp_server successfully.n"; // Upload a file if (ftp_put($ftp_conn, $remote_file, $local_file, FTP_BINARY)) { echo "Successfully uploaded $local_file.n"; } else { echo "Error uploading $local_file.n"; } // List files in root directory $file_list = ftp_nlist($ftp_conn, "/"); if ($file_list) { echo "Files in root directory:n"; foreach ($file_list as $file) { echo "$filen"; } } // Close connection ftp_close($ftp_conn); } else { echo "Could not log in to $ftp_server."; } ?>
  • 10. Reading and Writing Files in PHP Writing to a File  To write to a file in PHP, you can use the fwrite( ) function, which writes content to an open file.  To open a file, use the fopen( ) function. <?php $filename = "example.txt"; $content = "Hello, this is a sample text."; // Open the file for writing (creates the file if it doesn't exist) $file = fopen($filename, "w"); // Write content to the file if (fwrite($file, $content)) { echo "File written successfully."; } else { echo "Error writing to the file."; } // Close the file fclose($file); ?>
  • 11. File Modes •"w": Write-only. Opens and clears the file content (if the file exists) or creates a new file. •"w+": Read and write. Clears the file content or creates a new one. •"a": Write-only. Opens and writes to the end of the file (append mode). •"a+": Read and write. Writes to the end of the file. •"r": Read-only. Opens the file for reading. Fails if the file does not exist. •"r+": Read and write. Does not clear the file content.
  • 12. Reading from a File  To read content from a file, you can use the fread() function,  For smaller files, file_get_contents() can be used, which reads the entire file into a string. Reading with file_get_contents() <?php $filename = "example.txt"; // Read entire file content $content = file_get_contents($filename); if ($content !== false) { echo "File content:n$content"; } else { echo "Error reading the file."; } ?>
  • 13. Steps to Read a File Using fread() <?php $filename = "example.txt"; // Open the file for reading $file = fopen($filename, "r"); // Read file content if ($file) { $filesize = filesize($filename); $content = fread($file, $filesize); echo "File content:n$content"; } else { echo "Error opening the file."; } // Close the file fclose($file); ?>
  • 14.  fopen() Opens a file.  fwrite() Writes data to a file.  fread() Reads data from a file.  file_get_contents() Reads entire file content.  fgets() Reads a line from a file.  file_exists() Checks if a file exists.  unlink() Deletes a file.  chmod() Changes file permissions.  move_uploaded_file() Handles file uploads Common PHP File Functions
  • 15. DEVELOPING OBJECT-ORIENTED SCRIPT USING PHP create reusable and modular code by organizing it into objects. Let's go over the basic structure for creating an object-oriented script in PHP.  Classes: Blueprint for creating objects. Classes define properties (variables) and methods (functions) that can be used by the objects created from the class.  Objects: Instances of a class.  Properties: Variables within a class.  Methods: Functions defined inside a class that can
  • 16. <?php // Define a class class Car { // Properties public $make; public $model; public $year; // Constructor (automatically called when an object is created) public function __construct($make, $model, $year) { $this->make = $make; $this->model = $model; $this->year = $year; } // Method public function getCarInfo() { return "Car: " . $this->make . " " . $this->model . " (" . $this->year . ")"; } // Setter method public function setYear($year) { $this->year = $year; } // Getter method public function getYear() { return $this->year; } } // Create an object (instance of the Car class) $myCar = new Car("Toyota", "Corolla", 2020); // Accessing a method echo $myCar->getCarInfo(); //Output: Car: Toyota Corolla (2020) // Changing the year using a setter method $myCar->setYear(2022); // Accessing the updated value echo $myCar->getCarInfo(); ?> Output: Car: Toyota Corolla (2022)
  • 17. ($make, $model, and $year) and methods (getCarInfo, setYear, getYear).  Constructor: The __construct() method initializes an object when it is created. Here, it sets the car’s make, model, and year. Methods  getCarInfo() is a method that returns a string with the car’s details.  setYear() and getYear() are setter and getter methods to update and retrieve the value of the year property.  Object Instantiation: $myCar = new Car("Toyota", "Corolla", 2020); creates a new object of the Car class, passing initial values.  Accessing Methods and Properties: $myCar->getCarInfo(); accesses the object’s method, and $myCar->setYear(2022);
  • 18. EXCEPTION HANDLING  Exception handling is a mechanism in programming that allows a system to handle unexpected events or errors that occur during the execution of a program.  These unexpected events, known as exceptions, can disrupt the normal flow of an application.  Exception handling provides a controlled way to respond to these exceptions, allowing the program to either correct the issue or gracefully terminate. Why Do We Need Exception Handling? 1.Maintaining Application Flow: Without exception handling, an unexpected error could terminate the program abruptly. Exception handling ensures that the program can continue running or terminate gracefully. 2.Informative Feedback: When an exception occurs, it provides valuable information about the problem, helping developers to debug and users to understand the issue. 3.Resource Management: Exception handling can ensure that resources like database connections or open files are closed properly even if an error occurs. 4.Enhanced Control: It allows developers to specify how the program should respond to specific types of errors.
  • 19. Here is an example of a basic PHP try catch statement. try { // run your code here } catch (exception $e) { //code to handle the exception } finally { //optional code that always runs }
  • 20. PHP error handling keywords The following keywords are used for PHP exception handling.  Try: The try block contains the code that may potentially throw an exception. All of the code within the try block is executed until an exception is potentially thrown.  Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP runtime will then try to find a catch statement to handle the exception.  Catch: This block of code will be called only if an exception occurs within the try code block. The code within your catch statement must handle the exception that was thrown.  Finally: In PHP 5.5, the finally statement is introduced. The finally block may also be specified after or instead of catch blocks.  Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes. This is useful for scenarios like closing a database connection regardless if an exception occurred or not.
  • 21. PHP try catch with multiple exception types try { // run your code here } catch (Exception $e) { echo $e->getMessage(); } catch (InvalidArgumentException $e) { echo $e->getMessage(); }
  • 22. When to use try catch-finally Example for try catch-finally: try { print "this is our try block n"; throw new Exception(); } catch (Exception $e) { echo "something went wrong, caught yah! n"; } finally { print "this part is always executed n"; }