0% found this document useful (0 votes)
16 views39 pages

PHP JT 3rd Unit

This document provides an overview of using functions, classes, and objects in PHP, detailing the definition, creation, and types of functions including built-in and user-defined functions. It explains the importance of functions for code reusability, error detection, and maintenance, along with variable scope and the use of recursion. Additionally, it covers various PHP library functions related to strings, arrays, file systems, and date/time operations.

Uploaded by

dhanrajbhandge00
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)
16 views39 pages

PHP JT 3rd Unit

This document provides an overview of using functions, classes, and objects in PHP, detailing the definition, creation, and types of functions including built-in and user-defined functions. It explains the importance of functions for code reusability, error detection, and maintenance, along with variable scope and the use of recursion. Additionally, it covers various PHP library functions related to strings, arrays, file systems, and date/time operations.

Uploaded by

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

UnitIII Using Functions, Class- Objects, Forms in PHP:

PHP Functions
● A function is a block of code written in a program to perform
some specific task. OR
● PHP function is a piece of code that can be reused many
times.
● It can take input as an argument list and return value.
● There are thousands of built-in functions in PHP.
● Syntax:
function function_name()
{
executable code;
}
Why should we use functions?
Reusability:
● If we have a common code that we would like to use at various parts of
a program, we can simply contain it within a function and call it
whenever required.
● This reduces the time and effort of repetition of a single code.
● This can be done both within a program and also by importing the PHP
file, containing the function, in some other program
Easier error detection:
● Since, our code is divided into functions, we can easily detect in which
function, the error could lie and fix them fast and easily.
Easily maintained:
● As we have used functions in our program, so if anything or any line of
code needs to be changed, we can easily change it inside the function
and the change will be reflected everywhere, where the function is
called. Hence, easy to maintain.

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;
}

Types of functions:
1. Builtin function
2. User defined functions.

1. Builtin function:
● These functions provide us with built-in library functions. PHP provides
these functions in the installation package itself which makes this
language more powerful and useful. To use the properties of the
function we just need to call the function wherever required to fetch the
desired result.
● There are many built-in functions used in PHP such as Date, Numeric,
String, etc.
String Functions:
● These functions have a predefined functionality in PHP to work with
strings.
● PHP has various string functions such as strpos(), strncmp(), strrev(),
strlen(),
Date Function:
● These functions are predefined functionality in PHP where the format is
a UNIX date and time which is a human-readable format.
Numeric Functions:
● These functions have their own predefined logic provided by PHP
which is used for numeric operations.
● It will return the result either in Boolean form or in the numeric form.
● Some of the numeric functions include is_number(), number_format(),
round() ,etc.
Examples for Built-in functions:
<!DOCTYPE html>
<html>
<body>
<?php
print_r(str_split("Hi This is a test sample"));
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
echo strcmp("Hi this is test","Hi this is test");
?>
<p>If this function returns 0, the two strings are same.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
echo strpos("I love coding, I love php too!","coding");
?>
</body>
</html>

2. User-Defined
● These functions are used when the developer or programmer has to
execute their own logic of code.
● These functions are defined using the keyword function and inside the
function, a set of statements will be written to execute it when a
function call occurs.
● The function call can be made by just simply calling the function like
function _name(), and the function will get executed.

Creating and invoking(calling) User-Defined 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 for function without parameters:

Example for function with parameters:

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

<?php
myMessage();
function setHeight($minheight = 50)
{
echo "The height is : $minheight <br>";
}
//calling the function
setHeight(350); //Actual parameter
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
echo pi();
?>
Formal parameters actual parameters:
1. Formal Parameters: (function definition parameters)
● Formal parameters are variables that are used in the function
declaration to represent the values that the function expects when
it is called.
● They are defined within the parenthesis in the function.
● Formal parameters are placeholders for the values that will be
provided to the function when it is called.
● Example:
function addNumber($num1,$num2) //formal
parameters
{
Return $num1+$num2;
}
2. Actual parameters: (arguments passed to function)
● The concrete values or expressions provided to a function when it
is called are referred to as parameter.
● They are supplied inside the parentheses in the function call,
corresponding to the formal parameters in order.
● Example.
<?php
function addNumber($num1,$num2) //formal parameters
{
Return $num1+$num2;
}
$result=addNumber(5,3); //Actual parameters
?>

Functions and variable scope:

In PHP, variables can be declared anywhere in the script.

● The scope of a variable is the part of the script where the variable can be
referenced/used.
PHP has three different variable scopes:
● local
● global
● static
Global
● A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:
● Example: Variable with global scope:
The global and GLOBALS keyword is used to access a global variable from
within a function.
To do this, use the global keyword before the variables (inside the function):

Using global keyword:

<!DOCTYPE html>
<html>
<body>

<?php
$x = 5; // global scope

function myTest() {
global $x;
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>

</body>
</html>

● PHP also stores all global variables in an array called


$GLOBALS[index]. The index holds the name of the variable.
● This array is also accessible from within functions and can be used to
update global variables directly.

Using GLOBALS keyword:

<?php
$gv=10;
function myfun()
{
echo $GLOBALS['gv'];
}
myfun();

?>
Local Scope:
● A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
● Example: Variable with local scope: The program will generate an warning:

<!DOCTYPE html>
<html>
<body>

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<?php
//$x = 5;
//$y = 10;

function myTest() {
global $x;
global $y;
$x = 5;
$y = 1;
//$y = $x + $y;
}

myTest(); // run function


$y = $x + $y;
echo $y; // output the new value for variable $y
?>
</body>
</html>

PHP The static Keyword


● Normally, when a function is completed/executed, all of its variables are
deleted.
● However, sometimes we want a local variable NOT to be deleted.
● We need it for a further job.
● To do this, use the static keyword when you first declare the variable:
● Example:

<!DOCTYPE html>
<html>
<body>

<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
</body>
</html>

● Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.

Note: The variable is still local to the function.

PHP Recursive Function


● PHP also supports recursive function call like C/C++. In such a case, we call the
current function within the function. It is also known as recursion.
● Recursion is a common mathematical and programming concept. This has the
benefit of meaning that you can loop through data to reach a result.
● The developer should be careful with recursion functions as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power.
● However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.
● Example 1: Printing number

<?php
function display($number) {
if($number<=5){
echo "$number <br/>";
display($number+1);
}
}
display(1);
?>

Example 2 : Factorial Number

<?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);
?>
Library functions:
● Library Functions, also known as built-in functions, are PHP-includes
per-written code blocks that can be utilized for common tasks.
● They provide a wide range of features, eliminating the need to write
code from scratch for a variety of procedures.
● Everything from string manipulation to database access is covered.

1. String functions:
● strlen():
The strlen() function returns the length of a string.

● strpos():
The strpos() function finds the position of the first occurrence of a
string inside another string.
Note: The strpos() function is case-sensitive.
Syntax
strpos(string,find,start)
● strrev():
The strrev() function reverses a string.
Syntax
strrev(string)

2. array functions in php:


1. array()
● The array() function is used to create an array.
● In PHP, there are three types of arrays:
● Indexed arrays - Arrays with numeric index
● Associative arrays - Arrays with named keys
● Multidimensional arrays - Arrays containing one or more
arrays
● Syntax: Syntax for indexed arrays:
array(value1, value2, value3, etc.)
● Syntax for associative arrays:
array(key=>value,key=>value,key=>value,etc.)
2. array_fill() function:
● The array_fill() function fills an array with values.
● Syntax
array_fill(index, number, value)

3. array_push ()
● The array_push() function inserts one or more elements to
the end of an array.
● Tip: You can add one value, or as many as you like.
● Note: Even if your array has string keys, your added elements
will always have numeric keys (See example below).
3. File system functions:
● The file_get_contents():The file_get_contents() reads a file into a
string.
● This function is the preferred way to read the contents of a file into a
string. It will use memory mapping techniques, if this is supported by
the server, to enhance performance.
● Syntax
file_get_contents(path, include_path, context, start, max_length)
● The file_put_contents() writes data to a file.
● Syntax
file_put_contents(filename, data, mode, context)

4. Date and Time functions in php:


● The date/time functions allow you to get the date and time from the
server where your PHP script runs.
● You can then use the date/time functions to format the date and time in
several ways.

Note: These functions depend on the locale settings of your server.


Remember to take daylight saving time and leap years into
consideration when working with these functions.

1. The date_create() function.


● The date_create() function returns a new DateTime object.
● Syntax
date_create(time, timezone)

2. The date_date_set() function


● The date_date_set() function sets a new date.
● Syntax
date_date_set(object, year, month, day)

3. The date_default_timezone_get() function


● The date_default_timezone_get() function returns the default
timezone used by all date/time functions in the script.
● Syntax
date_default_timezone_get()
4. The date_default_timezone_set() function
● The date_default_timezone_set() function sets the default
timezone used by all date/time functions in the script.
● Syntax
date_default_timezone_set(timezone)

5. The date_diff() function


● The date_diff() function returns the difference between two
DateTime objects.
● Syntax
date_diff(datetime1, datetime2, absolute)

time() functions:
1. The time() function returns the current time in the number of seconds
since the Unix Epoch (January 1 1970 00:00:00 GMT).
2. The timezone_open() creates a new DateTimeZone object.
3. The timezone_name_get() returns the name of the timezone.
4. The timezone_location_get() returns location information for the given
timezone.

<?php
echo "1. Today is " . date("Y/m/d") . "<br>";
echo "2. Today is " . date("Y/m/d-H:i:sa") . "<br>"; //Note that the PHP date()
function will return the current date/time of the server!
echo "3. Today is " . date("Y.m.d") . "<br>";
echo "4. Today is " . date("Y-m-d") . "<br>";
echo "5. Today is " . date("l");
echo "<br>";
echo $days=date('N');
echo "<br>";

$date=date_create("2024-07-05");
date_add($date,date_interval_create_from_date_string("40 days"));
echo date_format($date, 'Y-m-d');
echo "<br>";

$dt = date_create('2019-01-01');
date_add($dt, date_interval_create_from_date_string('1 year 35 days'));
echo date_format($dt, 'Y-m-d');

echo "<br>";
echo date_format($date,"Y-M-D");
echo "<br>";

echo "<br>";
$date=date_create("2024-06-05");
echo date_format($date,"y-m-d");
echo "<br>";

$d=date_create("1947-06-05");
date_date_set($d,2024,06,05);
echo date_format($d,"Y/m/d");

echo "<br>";
echo date_default_timezone_get(); //UTC: coordinated Universal Time

echo "<br>";
$t=date_default_timezone_set("Asia/Bangkok");
echo “$t”;

echo "<br>";
$date1=date_create("2013-03-15");
$date2=date_create("2024-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");

echo "<br>";
$t=time();
echo($t . "<br>");
echo "<br>";

$tz=timezone_open("Europe/Paris");
echo timezone_name_get($tz);

echo "<br>";
$tz=timezone_open("Europe/Paris");
echo timezone_name_get($tz);

echo "<br>";
$tz=timezone_open("Europe/Paris");
print_r(timezone_location_get($tz));
?>
Create a Date From a String With strtotime()
● The PHP strtotime() function is used to convert a human readable date
string into a Unix timestamp

Create a Date With mktime()


● The PHP mktime() function returns the Unix timestamp for a date.
● The Unix timestamp contains the number of seconds between the Unix
Epoch (January 1 1970 00:00:00 GMT) and the time specified.
● Syntax
mktime(hour, minute, second, month, day, year)

PHP What is OOP?


● OOP stands for Object-Oriented Programming.
● Procedural programming is about writing procedures or functions that
perform operations on the data, while object-oriented programming is
about creating objects that contain both data and functions.
● Object-oriented programming has several advantages over
procedural programming:
❖ OOP is faster and easier to execute
❖ OOP provides a clear structure for the programs
❖ OOP helps to keep the PHP code DRY "Don't Repeat
Yourself", and makes the code easier to maintain, modify and
debug.
❖ OOP makes it possible to create full reusable applications
with less code and shorter development time
PHP - What are Classes and Objects?
● Classes and objects are the two main aspects of object-oriented
programming.
● Look at the following illustration to see the difference between
class and objects:
● Class
○ Car
● objects
○ Volvo
○ Audi
○ Toyota
● So, a class is a template for objects, and an object is an instance of a
class.
● When the individual objects are created, they inherit all the
properties and behaviors from the class, but each object will have
different values for the properties.

Creating and accessing a Class & Object , Object properties, object methods

Define a Class
● A class is defined by using the class keyword, followed by the name
of the class and a pair of curly braces ({}).
● All its properties and methods go inside the braces:
<?php
class Fruit {
// code goes here...
}
?>
● Below we declare a class named Fruit consisting of two properties
($name and $color) and two methods set_name() and get_name() for
setting and getting the $name property:
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>

Define Objects:
● Classes are nothing without objects! We can create multiple objects
from a class.
● Each object has all the properties and methods defined in the class,
but they will have different property values.
● Objects of a class are created using the new keyword.
● In the example below, $apple and $banana are instances of the class
Fruit:
<!DOCTYPE html>
<html>
<body>

<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}

$apple = new Fruit();


$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>

</body>
</html>
PHP - What is Inheritance?
● Inheritance in OOP = When a class derives from another class.
● The child class will inherit all the public and protected properties and
methods from the parent class.
● In addition, it can have its own properties and methods.
● An inherited class is defined by using the extends keyword.
● Let's look at an example:
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

// Strawberry is inherited from Fruit


class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>

Example Explained
● The Strawberry class is inherited from the Fruit class.
● This means that the Strawberry class can use the public $name and
$color properties as well as the public __construct() and intro() methods
from the Fruit class because of inheritance.
● The Strawberry class also has its own method: message().

PHP - Inheritance and the Protected Access Modifier


● protected properties or methods can be accessed within the class and by
classes derived from that class.
● What does that mean?Let's look at an example:
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->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"); // __construct() is
public
$strawberry->message(); // message() is public
$strawberry->intro(); // ERROR. intro() is protected
?>

● In the example above we see that if we try to call a protected method


(intro()) from outside the class, we will receive an error. public methods
will work fine!

Let's look at another example:


<!DOCTYPE html>
<html>
<body>

<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
// Call protected function from within derived class
$this -> intro();
}
}
$strawberry = new Strawberry("Strawberry", "red"); //__construct() is
public
$strawberry->message(); // message() is public and it calls intro() (which
is protected) from within the derived class
?>

</body>
</html>

The __construct Function


● A constructor allows you to initialize an object's properties upon creation of
the object.
● If you create a __construct() function, PHP will automatically call this
function when you create an object from a class.
● Notice that the construct function starts with two underscores (__)!
<!DOCTYPE html>
<html>
<body>

<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
echo "constructor created<br>";
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<?php
class Fruit {
public $name;
public $color;

function __construct($name, $color) {


$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>

</body>
</html>

PHP - The __destruct Function


● A destructor is called when the object is destructed or the script is
stopped or exited.
● If you create a __destruct() function, PHP will automatically call this
function at the end of the script.
● Notice that the destruct function starts with two underscores (__)!
● The example below has a __construct() function that is automatically
called when you create an object from a class, and a __destruct()
function that is automatically called at the end of the script:

<!DOCTYPE html>
<html>
<body>

<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.<br>";
echo "destructor is called object deleted";
}
}

$apple = new Fruit("Apple");


?>

</body>
</html>

You might also like