0% found this document useful (0 votes)
4 views58 pages

android application(MAD)

This document covers various concepts in PHP, including functions, classes, and object-oriented programming. It explains how to define and use functions, the difference between built-in and user-defined functions, and the principles of recursion, variable scope, and string manipulation. Additionally, it discusses object-oriented concepts such as classes, objects, inheritance, polymorphism, and access modifiers.

Uploaded by

sharathdevadig2
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)
4 views58 pages

android application(MAD)

This document covers various concepts in PHP, including functions, classes, and object-oriented programming. It explains how to define and use functions, the difference between built-in and user-defined functions, and the principles of recursion, variable scope, and string manipulation. Additionally, it discusses object-oriented concepts such as classes, objects, inheritance, polymorphism, and access modifiers.

Uploaded by

sharathdevadig2
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/ 58

Functions, Class- Objects,

Forms,Database Handling in PHP


UNIT 3
Functions in PHP
• Functions are reusable blocks of code in PHP that perform specific tasks
Defining & Creating a Function
syntax :
function function_name(parameters)
{
// Statements
}
• The functions using the function keyword followed by the function name, parentheses for
arguments and a code block within curly braces
• The parameters after function_name, separated by commas are optional

Example
function greet($name) {
echo "Hello, $name!";
}
greet("Alice"); // Output: Hello, Alice!
Function with argument(parameter)
Functions can accept zero or more arguments (inputs) passed within parentheses
when calling the function.
Example
function calculate_area($length, $width)
{
$area = $length * $width;
return $area;
}
$rectangle_area = calculate_area(5, 3); // Pass arguments (length, width)
echo $rectangle_area; // Output: 15 (assuming $area is returned)
Types of Functions:
1. Built-in Functions(Library functions): PHP provides a rich set of built-in
functions for various tasks like string manipulation, math operations, array
manipulation, file handling, and more.
Example:
<?php
echo strrev("dlrow olleH"); // Reverse string
echo str_repeat("Hoo", 2); // Repeat string
echo strtoupper("hooray!"); // String to uppercase
?>
2.User-Defined Functions: create own functions to encapsulate specific
functionalities within application.
Example: User-Defined Function with Default Arguments
function sum(int $x, int $y = 0) // $y has a default value of 0
{
return $x + $y;
}
$result1 = sum(5, 3); // Call with both arguments
$result2 = sum(10); // Call with only $x (using default value for $y)
echo $result1; // Output: 8
echo $result2; // Output: 10
Formal parameters vs
actual parameters in PHP
1.Formal Parameters(formal arguments):
• Definition: Formal parameters are the variables declared within the
function definition itself.
• These variables act as placeholders to receive the values passed when the
function is called.
• They are defined inside the function's parentheses following the function
name.

2. Actual Parameters (Actual Arguments):


• Definition: Actual parameters are the values that are passed to the
function when it's invoked (called). These values are provided within the
parentheses when calling the function
• They are placed inside the parentheses during the function call
Example:
<?php
function greet($name) { //$name is formal argument
echo "Hello, $name!";
}
$a="alice";
greet($a); //”alice” is actual argument

?>
Recursion in PHP
• Recursion in PHP is a programming technique where a function calls itself directly or indirectly.
• It's a powerful tool for solving problems that can be broken down into smaller sub problems of the
same type.
Example:
function factorial($n)
{
if ($n < 0)
{ // Base case (invalid input)
return -1;
} else if ($n == 0)
{ // Base case (factorial of 0 is 1)
return 1;
} else {
return $n * factorial($n - 1); // Recursive call
}
}
$result = factorial(5);
echo $result; // Output: 120
Function and variable scope
1. Function Scope:
• Function scope refers to the accessibility of variables declared within a function
definition.
• Variables defined inside a function are local to that function and cannot be
accessed directly from outside the function.
Example:
function greet($name) {
$message = "Hello, $name!"; // Variable $message is local to greet()
echo $message;
}
$global_name = "Alice";
greet($global_name); // This works because arguments can be passed
echo $message; // This will cause an error because $message is not accessible outside greet()
2. Variable Scope:
• Variable scope refers to the part of code where a variable is accessible and
can be referenced.
There are three main types of variable scope in PHP:
i. Local Scope:
 Variables declared within a function have local scope.
 Local variables are accessible just from the part of code where we define
them.
 If they’re outside of a function, they can be accessed by all code outside of
functions, classes, and so on.
 If a variable is inside a function, only that function can access the variable,
and its value is lost when the function returns.
Example:
function greet($name)
{
$message = "Hello, $name!";
echo $message;
}
ii. Global Scope:
• Variables declared outside of any function.
• They can be accessed from anywhere, including within functions.

Example:
$g=“This is global”;
function Message()
{
global $g;
echo $g;
}
Message();
iii. Static Scope (within functions):
• The static keyword can be used to declare variables within a function that
retain their values between multiple calls to the function.
• Declare using static keyword

Example:
function c()
{
Static $count=0;
$count++;
echo $count;
}
c();
Example

$global_message = "Global Greeting"; // Global variable


function say_hello()
{
static $count = 0; // Static variable
$count++;
echo $global_message " (called $count times)<br>";
}
say_hello(); // Output: Global Greeting (called 1 times)
say_hello(); // Output: Global Greeting (called 2 times)
echo $global_message;
// You can still access the global variable from anywhere
Library functions
• Library functions in PHP are pre-written functions that come bundled
with the PHP language itself.
• They provide a vast collection of functionalities for various tasks,
saving you time and effort from writing the code yourself.
• These functions are organized into categories based on their
purpose, making it easier to find the right tool for the job.
• String manipulation: Functions like strlen(), strpos(), substr(), etc. for
working with text data.
• Array manipulation: Functions like array_push(), array_pop(),
array_merge(), etc. for managing arrays.
• Mathematical functions: Functions like sqrt(), pow(), abs(), etc. for
performing mathematical calculations.
• Validation functions: Functions like is_numeric(), is_string(), etc. for
validating user input.
• Date and time functions: Functions like date(), time(), strtotime(),
etc. for working with dates and times.
Example:
$name = "Alice";
$nameLength = strlen($name);
echo "The length of the name is: $nameLength";
Date and Time Functions
• PHP provides a rich set of functions for working with dates and times
Getting Current Date and Time:
date(): This function formats the current date and time according to a specified format
string. You can customize the output using various format codes like "Y" for year, "m" for
month, "d" for day, "H" for 24-hour format, etc.
Example:
<?php
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
time(): This function returns the current timestamp, which is the number of
seconds elapsed since the Unix epoch (January 1, 1970 00:00:00 GMT).
Example:
<?php
$timestamp = time();
echo($timestamp);
echo "\n";
echo(date("F d Y h:i:s A", $timestamp));
?>
String in php
• Strings are fundamental building blocks in PHP for storing and
manipulating text data
Creating Strings:
• Double Quoted Strings: Enclose the text in double quotes ("). These
strings recognize escape sequences for special characters and variable
interpolation.
• For Example, $name = "Alice"; echo "Hello, $name!"; will print "Hello,
Alice!".
• Single Quoted Strings: Enclose the text in single quotes ('). They
interpret the string literally, including escape sequences as plain
characters
Operation on string
Accessing String Characters:
• Access individual characters of a string using their zero-based index within square brackets.
Example:
$str = "Hello";
echo $str[0];

String Formatting: Using double quoted string and embedding variables within curly braces
Example:
$name=“alice”;
$age=40;
$a=“hello $name You are $age year old”;
echo $a;
String Manipulation:
• Concatenation: Use the dot operator (.) to combine strings.
Example: $greeting = "Hello, " . $name;

Slicing:
• Extract a portion of a string using a colon (:).
Example:
$str = "Welcome";
$sub=$str[3:8]; echo $sub; //output: come
String Functions
PHP offers a wide range of functions for manipulating and working with
strings.
• str_replace(): Replaces all occurrences of a search string with a
replacement string.
• substr(): Extracts a portion of a string based on a starting index and
length.
• trim(): Removes whitespace (spaces, tabs, newlines) from the
beginning and end of a string.
• ltrim(): Removes whitespace from the beginning of a string.
• rtrim(): Removes whitespace from the end of a string.
String Searching and Manipulation:
• strpos(): Finds the position of the first occurrence of a substring within the
string.
• stripos(): Similar to strpos() but performs a case-insensitive search.
• explode(): Splits a string into an array of substrings based on a delimiter.
• implode(): Joins elements of an array into a string using a delimiter.
Case Conversion:
• strtoupper(): Converts all characters to uppercase.
• strtolower(): Converts all characters to lowercase.
Example:
$text=“This chair is red, I want white chair”;
$p=str_replace(“red”,”white”,$text);
echo $p;
Example:
$password1 = "secret";
$password2 = "SECRET";
if (strcmp($password1, $password2) === 0)
{
echo "Passwords match.";
}
else
{
echo "Passwords are different.";
}
Object oriented concept
Object in php
• Objects: Instances of the Class
• An object is an instance created from a class blueprint. It holds specific values for
the defined properties.
• We can create multiple objects from a single class, each with its own set of
property values.
• Accessing properties and methods of an object is done using the arrow operator
(->).

• Creating Objects:
• Use the new keyword followed by the class name and parentheses ().
• Assign the created object to a variable for later use.
$myCar = new Car(); // Create an object of the Car class
$myCar->color = "red"; // Set the color property
$myCar->model = "SUV"; // Set the model property
$myCar->moveForward(); // Call the method
Accessing the object:There are two ways to access members (properties and
methods) of an object:
i.Accessing Properties:
Use the arrow operator (->) followed by the property name.
syntax:
• $objectName->propertyName;
Example:
<?php
class Car {
public $color = "black"; // Default property value
public $model;
}
$myCar = new Car();
echo $myCar->color; // Outputs "black" (default value)
$myCar->model = "Sedan";
echo $myCar->model; // Outputs "Sedan" (after assignment)
?>
ii.Accessing Methods:
• Use the arrow operator followed by the method name and parentheses (). You
can optionally pass arguments to the method if it requires them.
syntax:
• $objectName->methodName([arguments]);
Example:
class Car
{
public function moveForward() {
echo "The car is moving forward.\n";
}
}
$myCar = new Car();
$myCar->moveForward(); // Calls the moveForward() method
Class in PHP
• classes are blueprints for creating objects.
• A class serves as a template that defines the characteristics (properties)
and functionalities (methods) of objects.
Creating a Class:
• Use the class keyword followed by the desired class name (always starts
with a capital letter).
• Enclose the class definition within curly braces {}. This is where we
define the properties and methods.
Example:
class Car {
// Properties (data)
public $color;
public $model;

// Methods (functions)
public function moveForward()
{
echo "The car is moving forward.\n";
}
}
Access Modifiers: The way we access properties and methods depends
on their visibility modifiers (public, private, protected).
• Public elements can be accessed from anywhere in code using the
object and the arrow operator.
• Private elements can only be accessed within the class itself (not from
outside the class).
• Protected elements can be accessed within the class and by inheriting
classes.
class User {
public $username;
private $password; // Only accessible within User class
protected function validatePassword() { // Accessible within User and inheriting classes

// Code to validate password


}
}

$user = new User;


$user->username = "johnDoe"; // Public property accessible
// $user->password = "secret"; // Gets an error (private)
Polymorphism:
• Polymorphism is a fundamental concept in object-oriented
programming (OOP) that allows objects of different classes to
respond differently to the same message (method call)

1. Method Overloading with __call():


• This method allows you to define a central function to handle calls to
methods that haven't been explicitly defined in the class.
• It partially simulates method overloading by checking the method
name and number of arguments received.
• In standard overloading, methods with the same name can have
different functionalities based on the arguments they receive.
• PHP doesn't allow this directly.
• Instead, it uses magic methods, specifically __call and optionally
__callStatic, to simulate overloading behavior.
• This method gets invoked whenever you try to call a method on the
object that doesn't exist within the class definition.
•The __call method receives two arguments:$method (string): The
name of the non-existent method being called.
•$arguments (array): An array containing the arguments passed
to the non-existent method.
Example
<?php
class MyClass {
public function __call($methodName, $arguments) {
echo "Method $methodName doesn't exist, but was called with arguments: " .
implode(', ', $arguments);
}
}
$obj = new MyClass();
$obj->doSomething(1, "hello"); // Outputs: Method doSomething doesn't exist, but was called with arguments: 1, hello
?>
2.Method overriding allows subclasses (child classes) to inherit methods from their
parent classes and redefine them to provide specialized behavior.
method overriding occurs when a subclass (child class) has the same method as the
parent class
Syntax:
class ParentClass {
public function someMethod() {
// Parent class implementation
}
}

class ChildClass extends ParentClass {


public function someMethod() {
// Child class implementation (overrides parent's method)
}
}
<php
class Animal {
public function makeSound() {
echo "Generic animal sound\n";
}
}
class Dog extends Animal {
public function makeSound() {
echo “boww!\n";
}
}
class Cat extends Animal {
public function makeSound() {
echo "Meow!\n";
}
}
$animals = [new Dog(), new Cat()];
foreach ($animals as $animal) {
$animal->makeSound(); // Calls the appropriate makeSound() based on the object's class
}
?>
Inheritance
Inheritance is allows to create new classes (subclasses) that inherit properties
and methods from existing classes (parent classes)
The extends Keyword: You use the extends keyword when defining a subclass
to specify the parent class it inherits from
Syntax:
class parentclassname{
// ... parent class properties and methods
}

class Childclassname extends parentclassname {


// ... subclass properties and methods
}
Example:
class Animal {
public function makeSound() {
echo "Generic animal sound.";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Woof!";
}
}
class Cat extends Animal {
public function makeSound() {
echo "Meow!";
}
}
$dog = new Dog();
$cat = new Cat();
$dog->makeSound(); // Outputs: Woof!
$cat->makeSound(); // Outputs: Meow!
Single inheritance
• Single inheritance allows a child class to inherit properties and
methods from a single parent class
• This promotes code reusability, reduces redundancy, and fosters clear
relationships between classes.
• The child class automatically inherits all public and protected
properties from the parent class
class Animal {
public $name;
public $color;

public function makeSound() {


echo "Generic animal sound";
}
}

class Dog extends Animal {


public function bark() {
echo "Woof!";
}
}

$dog = new Dog(); // No constructor call in Dog class


$dog->name = "Fido“; // Directly accessing inherited property
$dog->color = "brown"; // Directly accessing inherited property
$dog->makeSound(); // Calling inherited method
$dog->bark(); // Calling child class method
class Animal {
public $name;
public $color;
public function __construct($name, $color)
{ $this->name = $name;
$this->color = $color;
}
public function makeSound() {
echo "Generic animal sound";
}
}
class Dog extends Animal {
public function bark() {
echo "Woof!";
}
}
$dog = new Dog("Fido", "brown");
$dog->bark();
$dog->makeSound(); // Output: Generic animal sound. (inherited from Animal)
Multilevel Inheritance
• PHP itself does not directly support multilevel inheritance, which means a child
class can't inherit from more than one parent class.
• However, we can achieve a similar effect by chaining inheritance, creating a
hierarchical structure
Here's how it works:
• Base Class: Define a base class containing common properties and methods for
all descendant classes.
• Intermediate Class: Create an intermediate class that inherits from the base
class and adds its own functionalities specific to that level.
• Final Child Class: The final child class inherits from the intermediate class,
gaining access to properties and methods from both the base and intermediate
classes.
class Animal {
public function makeSound() {
echo "Generic animal sound.";
}
}

class Mammal extends Animal {


public function giveBirth() {
echo "Giving birth to live young.";
}
}
class Dog extends Mammal {
public function bark() {
echo "Woof!";
}
}
$dog = new Dog();
$dog->bark(); // Output: Woof!
$dog->giveBirth(); // Output: Giving birth to live young.
$dog->makeSound(); // Output: Generic animal sound. (inherited from Animal)
Constructor in php
• A constructor is a special type of method that is automatically called
when we create a new object of a class.
• It's primarily used for initialization purposes, such as setting up the
object's initial state or performing any necessary checks before the
object is used.
Declaring a Constructor:
• A constructor is defined using the _ _construct method name within
the class definition.
• It can optionally have arguments to receive values that will be used to
initialize the object's properties.
<?php
class Fruit
{
public $name;
public $color;
function _ _construct($name)
{
$this->name = $name;
}

function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple");
echo $apple->get_name();
?>
Destructors
• Destructors are special methods named _ _destruct that are invoked
automatically when an object ceases to be needed.
• A destructor is called when the object is destructed or the script is stopped
• This typically happens when the object goes out of scope or when the script
execution finishes.
• Destructors provide a mechanism to release resources that an object might
be holding, such as closing database connections, freeing memory
• Purpose of Destructors:
• Resource Cleanup: , or flushing buffers. This helps prevent memory leaks
and ensures efficient resource management.
• Finalization Tasks: You can use destructors to perform any final actions
needed before an object is destroyed, such as logging information or saving
data.
<?php
class Fruit
{
public $name;
public $color;
function _ _construct($name)
{
$this->name = $name;
}

function _ _destruct()
{
echo "The fruit is {$this->name}";
}
}
$apple = new Fruit("Apple");
?>
Form Handling: Creating HTML Form
• Create an HTML file (e.g., index.html) and define the form using
the <form> tag.
• A submission type specifying either a Get or Post method. It's
recommended to use POST for sensitive information like passwords.
• The destination URL to which the form data is to be submitted
• Include form elements like input fields, text areas, select boxes, etc.,
using appropriate HTML tags like <input>, <textarea>, and <select>.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Simple Form </title>
</head>
<body>
<form method="post" action="formtest.php">
What is your name?
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
Example:
<?php
echo <<<_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
<form method="post" action="formtest.php">
What is your name?
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
_END;
?>
• echo <<<_END..._END construct is used whenever multiline HTML
must be output.
• Inside of this multiline output is some standard code for commencing
an HTML document, displaying its title, and starting the body of the
document.
• This is followed by the form, which is set to send its data using the
Post method to the PHP program formtest.php, which is the name of
the program itself.
Handling HTML form data in PHP
• If you enter a name and click the Submit Query button in the HTML form,
absolutely nothing will happen other than the form being redisplayed. So
now it’s time to add some PHP code to process the data submitted by the
form.
• Expands on the previous program to include data processing.
• $_POST associative array for the field name having been submitted.
• element name of the $_POST array contains the value in $_POST['name'].
• The PHP isset function is used to test whether $_POST['name'] has been
assigned a value.
• If nothing was posted, the program assigns the value (Not entered);
<?php // formtest2.php
if (isset($_POST['name'])) $name = $_POST['name'];
else $name = "(Not entered)";
echo <<<_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
Your name is: $name<br>
<form method="post" action="formtest2.php">
What is your name?
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
_END;
?>
Database Handling Using PHP with MySQL
• A database is a structured collection of records or data stored in a
computer system and organized in such a way that it can be quickly
searched and information can be rapidly retrieved.
• Database contains one or more tables, each of which contains records or
rows. Within these rows are various columns or fields that contain the data
itself.
Table
• A subcontainer within a database that stores the actual data
Row
• A single record within a table, which may contain several fields
Column
• The name of a field within a row

You might also like