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

PHP UNIT 3

Unit 3 covers the use of functions, class-objects, and forms in PHP, detailing the creation and invocation of user-defined functions, parameter passing, and variable scope. It explains built-in and user-defined functions, recursion, and the handling of strings, date, and time in PHP. Additionally, it discusses variable scopes including local, global, and static variables, along with examples of string manipulation and formatting options.

Uploaded by

divyashree
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PHP UNIT 3

Unit 3 covers the use of functions, class-objects, and forms in PHP, detailing the creation and invocation of user-defined functions, parameter passing, and variable scope. It explains built-in and user-defined functions, recursion, and the handling of strings, date, and time in PHP. Additionally, it discusses variable scopes including local, global, and static variables, along with examples of string manipulation and formatting options.

Uploaded by

divyashree
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT 3

Using Functions, Class- Objects, Forms in PHP:


Functions in PHP, Function definition, Creating and
invoking user-defined functions, Formal
parameters versus Actual Parameters, Function
and variable scope, Recursion, Library functions,
Date and Time Functions.
Strings in PHP: What is String?, Creating and
Declaring String, String Functions.
UNIT 3

Functions in PHP

PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value. There are thousands of built-in functions in PHP.

In PHP, we can define Conditional function, Function within Function and Recursive
function also.

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times, like
in other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic many times. By
the use of function, you can write the logic only once and reuse it.

Easy to understand: PHP functions separate the programming logic. So it is easier to understand the
flow of the application because every logic is divided in the form of functions.

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 customised 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.

Creating a Function
• While creating a user defined function we need to keep few things in mind:
• 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
function myMessage() {
echo "Hello world!"; }
Call a Function
1
UNIT 3

To call the function, just write its name followed by parentheses ():

<html>
<body>
<?php
function myMessage()
{ echo "Hello world!";
}
myMessage();
?>
</body>
</html>

PHP Function Arguments

We can pass the information in PHP function through arguments which is separated by
comma.

PHP supports Call by Value (default), Call by Reference, Default argument


values and Variable-length argument list.

Syntax

function function_name($first_parameter, $second_parameter)


{ executable code;
}
Example

<?php
// function along with three parameters
function proGeek($num1, $num2, $num3)
{
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}
// Calling the function
// Passing three arguments
proGeek(2, 3, 5);
?>

Output:
The product is 30

Setting Default Values for Function parameter


PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this

2
UNIT 3

parameter in the function call.


Example:

<?php
// function with default parameter
function defGeek($str, $num=12)
{
echo "$str is $num years old \n";
}
// Calling the function
defGeek("Ram", 15);
// In this call, the default value 12
// will be considered
defGeek("Adam");
?>

Output:
Ram is 15 years old
Adam is 12 years old

Returning Values from Functions


Functions can also return values to the part of program from where it is called.
The return keyword is used to return value back to the part of program, from where it was
called. The returning value may be of any type including the arrays and objects. The return
statement also marks the end of the function and stops the execution after that and returns
the value.

Example:

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

Output:
The product is 30
Parameter passing to Functions
PHP allows us two ways in which an argument can be passed into a function:

3
UNIT 3

• Pass by Value: On passing arguments using pass by value, the value of the
argument gets changed within a function, but the original value outside the
function remains unchanged. That means a duplicate of the original value is
passed as an argument.
• Pass by Reference: On passing arguments as pass by reference, the original
value is passed. Therefore, the original value gets altered. In pass by reference
we actually pass the address of the value, where it is stored using ampersand
sign(&).
Example
<?php
// pass by value
function valGeek($num) {
$num += 2;
return $num;
}
// pass by reference
function refGeek(&$num) {
$num += 10;
return $num;
}
$n = 10;
valGeek($n);
echo "The original value is still $n \n";
refGeek($n);
echo "The original value changes to $n";
?>

Output:
The original value is still 10
The original value changes to 20

Formal and Actual Arguments

Sometimes the term argument is used for parameter. Actually, the two terms have a
certain difference.
• A parameter refers to the variable used in function’s definition, whereas an argument
refers to the value passed to the function while calling.
• 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 value of
the actual argument is assigned to the corresponding formal argument, from left to
right order.
• The number of formal arguments defined in the function and the number of actual
arguments passed should be same.

Example

4
UNIT 3

<?php
function addition($first, $second) {
$result = $first+$second;
echo "First number: $first \n";
echo "Second number: $second \n";
echo "Addition: $result \n";
}
# Actual arguments more than formal arguments
addition(10, 20, 30);
# Actual arguments fewer than formal arguments
$x=10;
$y=20;
addition($x);
?>
Output
First number: 10
Second number: 20
Addition: 30
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments
to function addition(), 1 passed in /home/cg/root/20048/main.php
on line 16 and exactly 2 expected in /home/cg/root/20048/main.ph

Function and variable scope


Variable Scopes: The scope of a variable is defined as its extent in the program within
which it can be accessed, i.e. the scope of a variable is the portion of the program within
which it is visible or can be accessed. Depending on the scopes, PHP has three variable
scopes.
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

5
UNIT 3

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

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;

6
UNIT 3

$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
// First function call
static_var();
// second function call
static_var();
?>

Output:
6
3
7
3

PHP Recursive Function

PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.

It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.

Example

<?php
function factorial($n)
{
if ($n < 0)
return -1; /*Wrong value*/
if ($n == 0)
return 1; /*Terminating condition*/
return ($n * factorial ($n -1));
}

echo factorial(5);
?>

7
UNIT 3

Output
120

PHP Date and Time


PHP date() function shows day, month and year altogether. Date and time are stored in
computer in UNIX Timestamp format. It calculates time in number of seconds on GMT
(greenwich mean time) i.e started from January 1, 1970, 00:00:00 GMT.

Syntax
string date ( string $format [, int $timestamp = time() ] )

Parameters

Paramete Description Required/Optional


r

Format Specifies the format of returned date and time required

Timestamp Current date can be used in place of timestamp optional

Example 1
<?php
$day =date('d/m/y');
Echo $day;
?>

Output:
09/08/18

Formatting options available in date() function: The format parameter of the date()
function is a string that can contain multiple characters allowing to generate the dates in
various formats. 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).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots
(.), slashes (/), or spaces to add additional visual formatting.
The following characters can be used along with the date() function to format the time
string:

8
UNIT 3

• 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).
• 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:
03:04:17
Dec,05,2017 03:04:17 PM
03:04 pm

PHP String
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP
supports only 256-character set and so that it does not offer native Unicode support. There are
4 ways to specify a string literal in PHP.
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)

1. Single-quote strings: This type of string does not process special characters inside
quotes.
<?php
$str1='Hello text
multiple line
text within single quoted string';
$str2='Using double "quote" directly inside single quoted string';
$str3='Using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3"; ?>

Output
Hello text multiple line text within single quoted string
Using double "quote" directly inside single quoted string
Using escape sequences \n in single quoted string

9
UNIT 3

Example
<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='Using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>

Output:

trying variable $num1


trying backslash n and backslash t inside single quoted string \n \t
Using single quote 'my quote' and \backslash

Note: In single quoted PHP strings, most escape sequences and variables will not be
interpreted. But, we can use single quote through \' and backslash through \\ inside
single quoted PHP strings.

2. Double-quote strings : Unlike single-quote strings, double-quote strings in PHP are


capable of processing special characters.

Example
<?php
$num1=10;
echo "Number is: $num1";
$str1="Hello text
multiple line
text within double quoted string";
$str2="Using double \"quote\" with backslash inside double quoted string";
$str3="Using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>

Output
Number is: 10
Hello text multiple line text within double quoted string
Using double "quote" with backslash inside double quoted string
Using escape sequences in double quoted string

• Now, you can't use double quote directly inside double quoted string.

10
UNIT 3

• We can store multiple line text, special characters and escape sequences in a
double quoted PHP string.
• In double quoted strings, variable will be interpreted.

3. Heredoc: The syntax of Heredoc (<<<) is another way to delimit PHP strings. An
identifier is given after the heredoc (<<< ) operator, after which any text can be written
as a new line is started. To close the syntax, the same identifier is given without any tab
or space.
Naming Rules
The identifier should follow the naming rule that it must contain only alphanumeric characters
and underscores, and must start with an underscore or a non-digit character. Example
<?php
$str = <<<Demo
It is a valid example
Demo; //Valid code as whitespace or tab is not valid before closing
identifier echo $str;
?>

Output:

It is a valid example

Below are the example with class and their variable

Example
<?php
class heredocExample{
var $demo;
var $example;
function construct()
{
$this->demo = 'DEMO';
$this->example = array('Example1', 'Example2', 'Example3');
}
}
$heredocExample = new heredocExample();
$name = 'Gunjan';

echo <<<ECO
My name is "$name". I am printing some $heredocExample->demo example.
Now, I am printing {$heredocExample->example[1]}.

11
UNIT 3

It will print a capital 'A': \x41


ECO;
?>

Output:

My name is "Gunjan". I am printing some DEMO example.


Now, I am printing Example2.
It will print a capital 'A': A

4. Nowdoc: Nowdoc is very much similar to the heredoc other than the parsing done in
heredoc. The syntax is similar to the heredoc syntax with symbol <<< followed by an
identifier enclosed in single-quote. The rule for nowdoc is the same as heredoc.

Example
The below example shows that newdoc does not print the variable's value.

<?php
class heredocExample{
var $demo;
var $example;
function construct()
{
$this->demo = 'DEMO';
$this->example = array('Example1', 'Example2', 'Example3');
}
}
$heredocExample = new heredocExample();
$name = 'Gunjan';
echo <<<ECO
My name is "$name". I am printing some $heredocExample->demo example.
Now, I am printing {$heredocExample->example[1]}.
It will print a capital 'A': \x41
ECO;
?>

Output:

The output of the above program will be like:

My name is "$name". I am printing some $heredocExample->demo example.


Now, I am printing {$heredocExample->example[1]}.

12
UNIT 3

It will print a capital 'A': \x41

PHP String Function Examples

1) PHP strtolower() function

The strtolower() function returns string in lowercase letter.

Syntax

string strtolower ( string $string )

Example

1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>

Output:
my name is khan

2) PHP strtoupper() function


The strtoupper() function returns string in uppercase letter.

Syntax
string strtoupper ( string $string )

Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>

Output:
MY NAME IS KHAN
3) PHP ucfirst() function
The ucfirst() function returns string converting first character into uppercase. It doesn't
change the case of other characters.

Syntax
1. string ucfirst ( string $str )

13
UNIT 3

Example
1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>

Output:
My name is KHAN

4) PHP lcfirst() function


The lcfirst() function returns string converting first character into lowercase. It doesn't change the
case of other characters.

Syntax
1. string lcfirst ( string $str )

Example
1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>

Output:
mY name IS KHAN

5) PHP ucwords() function


The ucwords() function returns string converting first character of each word into uppercase.

Syntax
1. string ucwords ( string $str )

Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>

Output:
My Name Is Sonoo Jaiswal

14
UNIT 3

6) PHP strrev() function


The strrev() function returns reversed string.

Syntax
1. string strrev ( string $string )

Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>

Output:
lawsiaj oonoS si eman ym

7) PHP strlen() function


The strlen() function returns length of the string.

Syntax
1. int strlen ( string $string )

Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>

Output:
ZZ24

15

You might also like