PHP JT 3rd Unit
PHP JT 3rd Unit
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.
Syntax:
function function_name()
{
executable code;
}
<?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
?>
● 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):
<!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();
</body>
</html>
<?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();
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
//$x = 5;
//$y = 10;
function myTest() {
global $x;
global $y;
$x = 5;
$y = 1;
//$y = $x + $y;
}
<!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.
<?php
function display($number) {
if($number<=5){
echo "$number <br/>";
display($number+1);
}
}
display(1);
?>
<?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)
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)
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
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;
}
}
</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}.";
}
}
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
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>
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
echo "constructor created<br>";
}
function get_name() {
return $this->name;
}
}
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
public $name;
public $color;
</body>
</html>
<!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";
}
}
</body>
</html>