android application(MAD)
android application(MAD)
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.
?>
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
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
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