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

PDF
Object Oriented PHP - PART-2
PPT
MySQL PHP Introduction Material for Course Web Programming
DOCX
Php advance
PPT
Php basics
PPSX
DIWE - File handling with PHP
PPTX
Files in php
PDF
PHP Programming and its Applications workshop
PPT
Php mysql
Object Oriented PHP - PART-2
MySQL PHP Introduction Material for Course Web Programming
Php advance
Php basics
DIWE - File handling with PHP
Files in php
PHP Programming and its Applications workshop
Php mysql

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

PPTX
Php.ppt
PPT
Php Tutorial
PPT
Php mysql
PPT
phpwebdev.ppt
PDF
Php Tutorials for Beginners
PDF
php AND MYSQL _ppt.pdf
PPTX
Introduction in php part 2
PPT
slidesharenew1
PPT
My cool new Slideshow!
PPTX
php programming.pptx
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PDF
Wt unit 4 server side technology-2
PDF
PHP Unit-1 Introduction to PHP
PPT
PPT
Phpwebdevelping
PPTX
php part 2
PDF
How to Write the Perfect PHP Script for Your Web Development Class
PPT
Phpwebdev
Php.ppt
Php Tutorial
Php mysql
phpwebdev.ppt
Php Tutorials for Beginners
php AND MYSQL _ppt.pdf
Introduction in php part 2
slidesharenew1
My cool new Slideshow!
php programming.pptx
PHP - DataType,Variable,Constant,Operators,Array,Include and require
Wt unit 4 server side technology-2
PHP Unit-1 Introduction to PHP
Phpwebdevelping
php part 2
How to Write the Perfect PHP Script for Your Web Development Class
Phpwebdev
Ad

More from BackiyalakshmiVenkat (10)

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

Recently uploaded (20)

PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Institutional Correction lecture only . . .
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
RMMM.pdf make it easy to upload and study
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Lesson notes of climatology university.
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
master seminar digital applications in india
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Renaissance Architecture: A Journey from Faith to Humanism
Institutional Correction lecture only . . .
Computing-Curriculum for Schools in Ghana
Pharmacology of Heart Failure /Pharmacotherapy of CHF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Pharma ospi slides which help in ospi learning
RMMM.pdf make it easy to upload and study
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Lesson notes of climatology university.
Anesthesia in Laparoscopic Surgery in India
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
master seminar digital applications in india
VCE English Exam - Section C Student Revision Booklet
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
human mycosis Human fungal infections are called human mycosis..pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
O5-L3 Freight Transport Ops (International) V1.pdf

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