0% found this document useful (0 votes)
2 views

phpunit3

This document provides an overview of PHP functions, including built-in and user-defined functions, parameters, variable scope, recursion, and library functions. It explains how to create and call functions, the importance of parameters, and the different types of variable scopes in PHP. Additionally, it covers string manipulation functions, date and time functions, and the basics of PHP classes and objects.
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)
2 views

phpunit3

This document provides an overview of PHP functions, including built-in and user-defined functions, parameters, variable scope, recursion, and library functions. It explains how to create and call functions, the importance of parameters, and the different types of variable scopes in PHP. Additionally, it covers string manipulation functions, date and time functions, and the basics of PHP classes and objects.
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/ 16

PHP and MySQL

Unit -3
1. PHP Functions
A function is a block of code written in a program to perform some specific task.. They take
information as parameter, executes a block of statements or perform operations on this parameters and
returns the result.

Syntax:
function function_name()
{
executable code;
}
PHP provides us with two major types of functions:

Built-in functions
PHP provides us with huge collection of built-in library functions. These functions are already
coded and stored in form of functions. To use those we just need to call them as per our requirement
like, var_dump, fopen(), print_r(), gettype() and so on.

User Defined Functions


Apart from the built-in functions, PHP allows us to create our own customized functions called
the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by simply calling it.

Why should we use functions?


 Reusability
 Easier error detection
 Easily maintained

To create a new function, use the function keyword

Calling a Function in PHP


Once a function is defined, it can be called any number of times, from anywhere in the PHP
code. Note that a function will not be called automatically. To call the function, use its name in a
statement; the name of the function followed by a semicolon.
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "Welcome to GSCH!";
}
/* Calling a PHP Function */
writeMessage();
?>
Output
Welcome to GSCH!
Puneeth R, GSC(A)H Page 1
PHP and MySQL

2. User-defined Functions in PHP


Its very easy to create your own PHP function
• User-defined functions are created by the programmer to perform specific tasks according to
their requirements.
• These functions are declared using the function keyword followed by a function name and a
block of code encapsulated within curly braces {}.
• They can accept parameters (input data) and return values (output data) using the return
statement.
• User-defined functions provide a way to encapsulate reusable code, promote modularity, and
enhance code readability and maintainability.
Creating a Function

While creating a user defined function:


 Any name ending with an open and closed parenthesis is a function.
 A function name always begins with the keyword function.
 To call a function we just need to write its name followed by the parenthesis
 A function name cannot start with a number. It can start with an alphabet or underscore.
 A function name is not case-sensitive.

Syntax:
function function_name()
{
executable code;
}

Example

<?php
// function along with three parameters
function addnum($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
return $product; //returning the product
}
// storing the returned value
$retValue = addnum(2, 3, 5);
echo "The product is $retValue";
?>

Output
The product is 30

Puneeth R, GSC(A)H Page 2


PHP and MySQL

3.Parameters
A parameter is an optional list of parameters that you define both pass information into the
procedure and send information out of procedure back to the calling program. Parameter is also known
as argument. When you define a parameter, you also specify the way in which it can be used.
An argument may be a literal, a variable or an expression

 The parameters in a function definition are also often called as formal arguments, and what is
passed is called actual arguments.
 The names of formal arguments and actual arguments need not be same.
 The number of formal arguments defined in the function and the number of actual arguments
passed should be same

Actual Parameters
The arguments that are passed in a function call are called actual arguments. These arguments
are defined in the calling function. These are the variables or expressions referenced in the parameter
list of a subprogram call. There is no need to specify datatype in actual parameter.

Formal Parameters
These are the variables or expressions referenced in the parameter list of a subprogram
specification. The datatype of the receiving value must be defined.

Puneeth R, GSC(A)H Page 3


PHP and MySQL

4. Function and variable scope

The scope of a variable is defined as its range in the program under which it can be accessed. In other
words, "The scope of a variable is the portion of the program within which it is defined and can be
accessed."

PHP has three types of variable scopes:


1. Local variable
2. Global variable
3. Static variable

Local variables: The variables declared within a function are called local variables to that function
and have their scope only in that particular function. In simple words, it cannot be accessed outside
that function. Any declaration of a variable outside the function with the same name as that of the one
within the function is a completely different variable. For now, consider a function as a block of
statements.
Example:
<?php

$num = 60;

function local_var() {

// This $num is local to this function


// the variable $num outside this function
// is a completely different variable
$num = 50;
echo "local num = $num <br>";
}

local_var();

// $num outside function local_var() is a


// completely different variable than that of
// inside local_var()
echo "Variable num outside local_var() function is $num \n";

?>

Output
local num = 50
Variable num outside local_var() function is 60

Puneeth R, GSC(A)H Page 4


PHP and MySQL

Global variables
The variables declared outside a function are called global variables. These variables can be
accessed directly outside a function. To get access within a function, we need to use the “global”
keyword before the variable to refer to the global variable.
Example
<?php
$num = 20;
// Function to demonstrate use of global variable
function global_var() {
// We have to use global keyword before the variable $num to access within the function
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>
Output:
Variable num inside function : 20
Variable num outside function : 20

Static variable It is the characteristic of PHP to delete the variable, once it completes its execution
and the memory is free. But sometimes we need to store the variables even after the completion of
function execution. To do this, we use static keywords and the variables are called static variables. PHP
associates a data type depending on the value for the variable.
Example:
<?php
// Function to demonstrate static variables
function static_var() {
// Static variable
static $num = 5;
$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
static_var(); // First function call
static_var(); // second function call
?>
Output:
6
3
7
3

Puneeth R, GSC(A)H Page 5


PHP and MySQL

5.Recursion Functions in PHP


Recursion functions in PHP allow a function to call itself during its execution. A recursive
function is such a function that calls itself until a certain condition is satisfied. In PHP, it is possible to
defines a recursive function
Benefits of Recursive Functions:

Modularity:
Recursive functions break down complex problems into simpler sub-problems, promoting modular and
reusable code.
Readability:
Recursive solutions often mirror the problem's natural structure, enhancing code readability.
Reduced Redundancy:
Recursive functions help eliminate redundant code by addressing common patterns through recursion.

Considerations for Recursive Functions:

Memory Usage:
Recursive functions may consume more memory due to the function call stack. Tail recursion
optimization can mitigate this concern in some cases.
Performance:
Recursive solutions may not always be the most performant. Evaluate alternative approaches for
specific scenarios.
Recursive functions in PHP with parameters offer a powerful mechanism for solving problems that
exhibit recursive patterns.
The syntax for a recursive function is similar to that of a regular function. The key difference lies in the
function calling itself within its own body. Here's a basic example of calculating the factorial of a
number:

Example : PHPscript to find the factorial of a number.

<?php
$n=4;
$f=1;
for($i=1;$i<=$n;$i++)
{
$f*=$i;
}
echo "Factorial of the Given Number is $f";
?>

Output

Factorial of the Given Number is 24

Puneeth R, GSC(A)H Page 6


PHP and MySQL

6. PHP Library functions


Library functions are part of the PHP library and can be used by anyone. A function receives a
list of arguments separated by commas.
A PHP library is a collection of already written programs and classes that are used for particular tasks
and operations in web applications. PHP libraries also enhance functionality by providing interfaces and
problem solving techniques.
Here are some examples of commonly used functions in PHP with detailed explanations:

 strlen() Description: This function is used to get the length of a string.


Example:
$str = "Hello, World!";
$length = strlen($str);
echo "The length of the string is: " . $length;
Output:
The length of the string is: 13

 array_push() Description: This function adds one or more elements to the end of an array.
Example:
$fruits = array("apple", "banana");
array_push($fruits, "orange", "mango");
print_r($fruits);
Output
Array ( [0] => apple [1] => banana [2] => orange [3] => mango )

 date() Description: This function is used to format and display the current date and time.
Example:
echo date("Y-m-d H:i:s");
Output:
2021-09-15 15:30:45 (The output will vary based on the current date and time)

 rand() Description: This function generates a random number between a specified range.
Example:
$randomNumber = rand(1, 100);
echo $randomNumber;
Output:
// A random number between 1 and 100

 file_get_contents() Description: This function reads the contents of a file and returns it as a
string.
Example:
$content = file_get_contents("file.txt");
echo $content;
Output:
The content of the "file.txt" file

Puneeth R, GSC(A)H Page 7


PHP and MySQL

 count() Description: This function returns the number of elements in an array.


Example:
$fruits = array("apple", "banana", "orange");
$count = count($fruits);
echo "The number of fruits is: " . $count;
Output:
The number of fruits is: 3

7. Date and Time function()


Date and time are some of the most frequently used operations in PHP while executing SQL
queries or designing a website etc. PHP serves us with predefined functions for these tasks. Some of the
predefined functions in PHP for date and time are discussed below.

PHP date() Function: The PHP date() function converts timestamp to a more readable date and
time format.
Syntax:
date(format, timestamp)

The format parameter in the date() function specifies the format of returned date and time.
The timestamp is an optional parameter, if it is not included then the current date and time will be used.
Date-related formatting characters that are commonly used in the format string:

d: Represents day of the month; two digits with leading zeros (01 or 31).
D: Represents day of the week in the text as an abbreviation (Mon to Sun).
m: Represents month in numbers with leading zeros (01 or 12).
M: Represents month in text, abbreviated (Jan to Dec).
y: Represents year in two digits (08 or 14).
Y: Represents year in four digits (2008 or 2014).

Example
<?php
echo "Today's date in various formats:" . "\n";
echo date("d/m/Y") . "\n";
echo date("d-m-Y") . "\n";
echo date("d.m.Y") . "\n";
echo date("d.M.Y/D");
?>

time()
PHP time() Function: The time() function is used to get the current time as a Unix timestamp
The following characters can be used along with the time() function to format the time string:

h: Represents hour in 12-hour format with leading zeros (01 to 12).


H: Represents hour in 24-hour format with leading zeros (00 to 23).
i: Represents minutes with leading zeros (00 to 59).
Puneeth R, GSC(A)H Page 8
PHP and MySQL

s: Represents seconds with leading zeros (00 to 59).


a: Represents lowercase antemeridian and post meridian (am or pm).
A: Represents uppercase antemeridian and post meridian (AM or PM).
Example
<?php
echo date("h:i:s") . "\n";
echo date("M,d,Y h:i:s A") . "\n";
echo date("h:i a");
?>
Output:
1512486297
December 05, 2017 03:04:57 PM

8. String
String is considered a data type, which in general is a sequence of multiple characters that can
contain whitespaces, numbers, characters, and special symbols. For example, “Hello World!”
 strlen() Function
It returns the length of the string i.e. the count of all the characters in the string including whitespace
characters.
Syntax
strlen(string or variable name);

 strrev() Function
It returns the reversed string of the given string.
Syntax
strrev(string or variable name);

 trim(), ltrim(), rtrim(), and chop() Functions


It removes white spaces or other characters from the string. They have two parameters: one string and
another charList, which is a list of characters that need to be omitted.
trim(): Removes characters or whitespaces from both sides.
rtrim() & chop(): Removes characters or whitespaces from the right side.
ltrim(): Removes characters or whitespaces from the left side.

Syntax
rtrim(string, charList)
ltrim(string, charList)
trim(string, charList)
chop(string, charList)

 strtoupper() and strtolower() Function


It returns the string after changing the cases of its letters.
strtoupper(): It returns the string after converting all the letters to uppercase.
strtolower(): It returns the string after converting all the letters to lowercase.
Syntax
strtoupper(string)
strtolower(string)

Puneeth R, GSC(A)H Page 9


PHP and MySQL

 str_split() Function
It returns an array containing parts of the string.
Syntax
str_split(string, length);

 str_word_count() Function
It is used to return information about words used in a string like the total number of words in the string,
positions of the words in the string, etc.
Syntax
str_word_count ( $string , $returnVal, $chars );

 strpos() Function
This function helps us to find the position of the first occurrence of a string in another string.
Syntax
strpos(original_str, search_str, start_pos);

 str_replace() Function
It is used to replace all the occurrences of the search string or array of search strings by replacement
string or array of replacement strings in the given string or array respectively.
Syntax
str_replace ( $searchVal, $replaceVal, $subjectVal, $count );

 ucwords() Function
It is used to convert the first character of every word in a string to upper-case.
Syntax
string ucwords ( $string, $separator )

Example: PHP script to implement atleast seven string functions.


<?php
$str="Government science COLLEGE hassan ";
$str1=$str;
$str=strtoupper($str);
echo $str."</br>";
$str=strtolower($str);
echo $str."</br>";
$str=ucfirst($str1);
echo $str."</br>";
$str=ucwords($str1);
echo $str."</br>";
$str=strrev($str1);
echo $str."</br>";
$str=strlen($str1);
echo $str."</br>";
$str=lcfirst($str1);
echo $str."</br>";
?>

Puneeth R, GSC(A)H Page 10


PHP and MySQL

9. PHP Class and Objects


A class is the template description of its objects. It includes the properties and functions that
process the properties. An object is the instance of its class. It is characterized by the properties and
functions defined in the class.
PHP Class
Classes are the blueprints of objects. One of the big differences between functions and classes is
that a class contains both data (variables) and functions that form a package called an: „object‟.
Class is a programmer-defined data type, which includes local methods and local variables.
Class is a collection of objects. Object has properties and behavior.

Syntax: We define our own class by starting with the keyword „class‟ followed by the name you want to
give your new class.

<?php
class person {

}
?>

Object is a compound data type (along with arrays). Values of more than one types can be stored
together in a single variable. Object is an instance of either a built-in or user defined class. In addition to
properties, class defines functionality associated with data.

Syntax

To declare an object of a class we need to use new statement


class myclass
{
..
..
}
$obj=new myclass;

Creating and Accessing Class and objects

Example

Given below is the complete PHP script that defines Book class, declares two objects and calls the
member functions.
<?php
class Book {

/* Member variables */
var $price;
var $title;

Puneeth R, GSC(A)H Page 11


PHP and MySQL

/* Member functions */
function setPrice($par){
$this->price = $par;
}

function getPrice(){
echo $this->price ."\n";
}

function setTitle($par){
$this->title = $par;
}

function getTitle(){
echo $this->title ."\n";
}
}

$b1 = new Book;


$b2 =new Book;

$b1->setTitle("PHP Programming");
$b1->setPrice(450);
$b2->setTitle("PHP Fundamentals");
$b2->setPrice(275);
$b1->getTitle();
$b1->getPrice();
$b2->getTitle();
$b2->getPrice();
?>

Output
PHP Programming
450
PHP Fundamentals
275

10. Object Properties in PHP


Class member variables are called properties. They may be referred to using other terms such as
fields, but for the purposes of this reference properties will be used. They are defined by using at least
one modifier , optionally followed by a type declaration, followed by a normal variable declaration.
This declaration may include an initialization, but this initialization must be a constant value.Within
class methods non-static properties may be accessed by using -> (Object Operator): $this->property
(where property is the name of the property).

Puneeth R, GSC(A)H Page 12


PHP and MySQL

We call properties to the variables inside a class. Properties can accept values like strings, integers, and
booleans (true/false values), like any other variable.
<?php
//example to access properties of a class
class Birds {
// properties
public $birdsFly = 'sky';
public $birdsSound = 'vocal';
public $birdsBuildNests = 'trees';
//methods
public function birdDoes()
{
echo 'Bird';
}
}
//object of class is declared
$obj = new Birds();
//properties of class Bird are accessed using object
echo '<br> Bird Flies = '.$obj->birdsFly;
echo '<br> Bird Makes Sound = '.$obj->birdsSound;
echo '<br> Bird Build Nests = '.$obj->birdsBuildNests;
?>
Output:

Bird Flies = Sky


Bird Makes Sound = Vocal
Bird Build Nests = trees

11. Methods of Object in PHP


We can define member functions in a class. These functions can then be called from an object.
These functions are called as methods of a class. These functions can be public, private or protected.
By default is public. Also while declaring the function we declare it as
Syntax:

public function functionaname() {


//statements
}
Example:
class Bird{
public $birdsFly;
{
//method 1 - get Method1
public function get_birdFlies()
{
return $this->birdsFly;
Puneeth R, GSC(A)H Page 13
PHP and MySQL

}
}
//object of class is declared
$obj = new Birds();
$obj->set_birdFlies('Fly');
echo '<br> Bird Flies = '.$obj->get_birdFlies();
Output:

Bird Flies = Fly

12. Overloading
Overloading is an Object-Oriented concept in which two or more methods have the same method
name with different arguments or parameters (compulsory) and return type (not necessary).
 All overloading methods must be defined as Public.
 After creating the object for a class, we can access a set of entities that are properties or methods
not defined within the scope of the class. Such entities are said to be overloaded properties or
methods, and the process is called as overloading.
Types of Overloading in PHP: There are two types of overloading in PHP.
 Property Overloading
 Method Overloading
Property Overloading: PHP property overloading is used to create dynamic properties in the object
context. For creating these properties no separate line of code is needed.
Method Overloading: It is a type of overloading for creating dynamic methods that are not declared
within the class scope.
<?php
class GFG {
public function __call($member, $arguments) {
$numberOfArguments = count($arguments);
if (method_exists($this, $function = $member.$numberOfArguments)) {
call_user_func_array(array($this, $function), $arguments);
}
}
private function multiply($argument1) {
echo $argument1;
}
private function multiply2($argument1, $argument2) {
echo $argument1 * $argument2;
}
}
$class = new GFG;
$class->multiply(2);
$class->multiply(5, 7);
?>
Output : 35

Puneeth R, GSC(A)H Page 14


PHP and MySQL

13. Inheritance
Inheritance is an important principle of object oriented programming methodology. Using this
principle, relation between two classes can be defined. PHP supports inheritance in its object model. In
PHP where a class (subclass or child class) can inherit properties and methods from another class
(superclass or parent class). It enables code reusability and promotes hierarchical relationships between
classes.

PHP uses extends keyword to establish relationship between two classes.


Syntax
class B extends A
where A is the base class (also called parent called) and B is called a subclass or child class. Child class
inherits public and protected methods of parent class.

Single Inheritance:
PHP supports single inheritance, meaning a class can inherit from only one parent class at a time.

Multiple Inheritance:
PHP does not support multiple inheritance where a class can inherit from multiple parent classes
simultaneously.

Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
}

class Strawberry extends Fruit {


public function message() {
echo "Am I a fruit or a berry? ";
}
}

// Try to call all three methods from outside class


$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message(); // OK. message() is public
?>

Puneeth R, GSC(A)H Page 15


PHP and MySQL

14. Constructors
A constructor is a special method. When a new object is created this method is invoked
automatically. There is no need for calling the method explicitly from an object.
The __construct() function doesn‟t have any return value.
Syntax:

_ _construct();// double underscores are used


Parameterized Constructor
The member variables of $b1 have been initialized without having to call setTitle() and setPrice()
methods, because the constructor was called as soon as the object was declared.
Constructor Overloading
Method overloading is an important concept in object-oriented programming, where a class may have
more than one definitions of constructor, each having different number of arguments.

The __destruct() Function


The _ _destruct() function doesn‟t have any parameters, neither does it have any return value. The fact
that the __destruct() function is automatically called when any object goes out of scope can be
verified by putting var_dump($this) inside the function. It is used to destroy the object once
used.

Example: PHP script to implement constructor and destructor


<?php
class Person
{
private $fname;
private $lname;
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
public function __destruct(){
echo "Destroying Object...";
}
public function showName() {
echo "My name is: " . $this->fname . " " . $this->lname . "<br/>";
}
}
$name= new Person("Sachin", "Dhoni");
$name->showName();
?>
Output
Initializing the object
My name is Sachin Dhoni
Destroying Object

Puneeth R, GSC(A)H Page 16

You might also like