object oriented programming in PHP & Functions

BackiyalakshmiVenkat 18 views 22 slides Sep 23, 2024
Slide 1
Slide 1 of 22
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22

About This Presentation

object oriented programming in PHP & Functions in PHP


Slide Content

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

Managing Files USING FTP in PHP 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 "$file\n"; } } // 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 Object-oriented programming (OOP) in PHP allows you to 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 operate on object properties. Visibility : Properties and methods can be marked as public, private, or protected to control access.

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

Class Declaration : The Car class is defined with properties ($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); modifies its property.

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? 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. Informative Feedback:  When an exception occurs, it provides valuable information about the problem, helping developers to debug and users to understand the issue. Resource Management:  Exception handling can ensure that resources like database connections or open files are closed properly even if an error occurs. 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"; }
Tags