phpunit3
phpunit3
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.
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
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.
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."
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() {
local_var();
?>
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;
$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
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.
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:
<?php
$n=4;
$f=1;
for($i=1;$i<=$n;$i++)
{
$f*=$i;
}
echo "Factorial of the Given Number is $f";
?>
Output
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
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:
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);
Syntax
rtrim(string, charList)
ltrim(string, charList)
trim(string, charList)
chop(string, charList)
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 )
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
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;
/* 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->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
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:
}
}
//object of class is declared
$obj = new Birds();
$obj->set_birdFlies('Fly');
echo '<br> Bird Flies = '.$obj->get_birdFlies();
Output:
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
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.
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;
}
}
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: