PHP Unit 3_4
PHP Unit 3_4
Functions
Strings
Class & Objects
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
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.
Built-in functions, also called predefined or library functions, are included in PHP by default.
They perform common tasks like handling strings, arrays, files, math operations, and databases.
These functions save time and effort as they are already implemented and available for use.
PHP offers a vast range of built-in functions, providing developers with tools to complete tasks
quickly and efficiently.
Example:
$string = "Hello, world!";
$length = strlen($string);
// Built-in function to find the length of a string
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.
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.
Any valid PHP code may appear inside a function, even other functions and class definitions.
Functions need not be defined before they are referenced, except when a function is conditionally
defined.
When a function is defined in a conditional manner, its definition must be processed prior to being
called.
All functions and classes in PHP have the global scope - they can be called outside a function
even if they were defined inside and vice versa.
A function may be defined using syntax such as the following:
function functionname()
{
//code to be executed
}
Example:
function greet($name) {
return "Hello, $name!";
}
Function arguments
Information may be passed to functions via the argument list, which is a comma-delimited list of
expressions. The arguments are evaluated from left to right, before the function is actually called
(eager evaluation).
PHP supports passing arguments by value (the default), passing by reference, and default
argument values. Variable-length argument lists and Named Arguments are also supported.
The list of function arguments may include a trailing comma, which will be ignored. That is
particularly useful in cases where the list of arguments is long or contains long variable names,
making it convenient to list arguments vertically.
By default, function arguments are passed by value (so that if the value of the argument within the
function is changed, it does not get changed outside of the function). To allow a function to
modify its arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend an ampersand (&) to the
argument name in the function definition:
A function may define default values for arguments using syntax similar to assigning a variable.
The default is used only when the parameter is not specified; in particular, note that passing null
does not assign the default value.
The default value must be a constant expression, not (for example) a variable, a class member or a
function call.
Note that any optional arguments should be specified after any required arguments, otherwise they
cannot be omitted from calls.
PHP has support for variable-length argument lists in user-defined functions by using the ... token.
Argument lists may include the ... token to denote that the function accepts a variable number of
arguments. The arguments will be passed into the given variable as an array.
Function parameters are placeholders or variables declared within the parentheses of a function. They
define the input required by the function when it’s called and pass values or variables into the function for
processing.
To call a function, first make sure the function is defined in your PHP code. Functions are defined before
they are called, either in the same file or in an included file.
Then, add the function name followed by parentheses that may contain any required arguments.
In PHP, function and variable scope determine where variables can be accessed and modified within the
code.
1. Local Scope:
Variables declared inside a function are local to that function. They are only accessible within the
function's code block.
Any changes made to a local variable within a function do not affect variables with the same name
outside the function.
2. Global Scope:
Variables declared outside of any function are considered global. They are accessible from
anywhere within the script, including inside functions.
However, using global variables extensively can make your code harder to understand and
maintain. It's generally recommended to use local variables and function arguments whenever
possible.
3. Static Scope (Within Functions):
Static variables declared within a function retain their value between function calls, unlike local
variables which are recreated each time the function is called.
This allows you to maintain state within a function across multiple calls.
Recursion
It is possible to call recursive functions in PHP.
In PHP, recursion refers to a programming technique where a function calls itself directly or indirectly.
This creates a loop-like behavior, but with some key differences.
Concept of Recursion:
A recursive function has a base case, which is a condition that stops the recursive calls and returns a final
result.
The recursive case involves the function calling itself with modified arguments that bring it closer to the
base case. This creates a series of nested function calls.
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For
example, factorial of 5 (written as 5!) is 5 * 4 * 3 * 2 * 1 = 120.
function factorial($n) {
if ($n === 0) { // Base case: factorial of 0 is 1
return 1;
} else {
// Recursive case: call factorial with n-1, multiply by n
return $n * factorial($n - 1);
}
}
$number = 5;
$result = factorial($number);
Explanation:
factorial(5) is called.
Since 5 is not equal to 0 (not the base case), it enters the recursive case.
The function calls itself with factorial(4).
Following the same logic, factorial(4) calls factorial(3).
This continues until factorial(0) is called.
At factorial(0), the base case is met, returning 1.
factorial(1) now receives 1 (from factorial(0)) and returns 1 (since 1! is 1).
factorial(2) receives 1 (from factorial(1)) and returns 2 (1 * 2).
This process continues up the chain of recursive calls.
Finally, factorial(5) receives the result from factorial(4) (which is the accumulated product from previous
calls) and returns 5 * 120 (120 being the result of factorial(4)).
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 (24).
Y: Represents year in four digits (2024).
The time() function is used to get the current time as a Unix timestamp (the number of seconds since the
beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
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).
o For the remaining functions and additional information, please refer to::
o https://www.php.net/manual/en/ref.strings.php
Class &Objects in PHP: What is Class & Object, Creating and accessing a Class &Object, Object
properties, object methods, Overloading, inheritance, Constructor and Destructor
PHP includes a complete object model. Some of its features are: visibility, abstract and final classes and
methods, additional magic methods, interfaces, and cloning.
PHP treats objects in the same way as references or handles, meaning that each variable contains an
object reference rather than a copy of the entire object.
Declaring a Class
A class definition includes the class name and the properties and methods of the class. Here’s the syntax
for a class definition:
Syntax:
class classname{
// properties;
//methods
}
A class may contain its own constants, variables called "properties", and functions called "methods".
Defining Properties
Class member variables are called properties. They are defined by using at least one modifier (such as
Visibility, Static Keyword) followed by a type declaration, followed by a normal variable declaration.
Class properties may be defined as public, private, or protected. Properties declared without any explicit
visibility keyword are defined as public.
Example:
public $var1 = 'hello ';
Declaring Methods
A method is a function defined inside a class. Although PHP imposes no special restrictions, most
methods act only on data within the object in which the method resides. Within a method, the $this
variable contains a reference to the object on which the method was called. Methods use the $this
variable to access the properties of the current object and to call other methods on that object.
To create a new object from a class, use the new statement to instantiate a class.
Example:
<?php
class SimpleClass
{
// property declaration
public $var = ‘value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
$newClass1 = new SimpleClass; //creating a new object for the class
$newClass1->displayVar();
?>
Consider a class Book to hold information about its title and author. The class Book is defined as:
class Book {
// Define properties (variables) to hold book information
public $title;
public $author;
Now, you can create an object (instance) of the Book class. Here's how to create an object:
Constructors and destructors are special methods used in object-oriented programming (OOP) to manage
the lifecycle of an object in PHP.
Constructors:
PHP allows developers to declare constructor methods for classes. Classes which have a
constructor method call this method on each newly-created object, so it is suitable for any
initialization that the object may need before it is used.
A constructor is a special method with the same name as the class (often denoted by __construct).
It's called automatically whenever a new object of that class is created using the new keyword.
The primary purpose of a constructor is to:
Initialize the object's properties with starting values.
Perform any other necessary setup tasks for the newly created object.
Destructors:
PHP possesses a destructor concept similar to that of other object-oriented languages, such as
C++. The destructor method will be called as soon as there are no other references to a particular
object, or in any order during the shutdown sequence.
A destructor is a special method with the name __destruct.
It's called automatically when an object goes out of scope or when the script execution ends.
The main purpose of a destructor is to:
Release resources associated with the object (e.g., closing files, database connections).
Perform any necessary cleanup tasks before the object is destroyed.
Example:
<?php
class Circle { Output:
public $radius;
function __construct($radius=5){
echo "In Constructor <br>";
$this->radius = $radius;
}
function __destruct(){
echo "in Desctuctor <br>";
}
function get_Area() {
return pi() * pow($this->radius, 2);
}
function get_Circumference() {
return 2 * pi() * $this->radius;
}
}
$circle1 = new Circle();
$circle = new Circle(15);
echo "Area: " . $circle->get_Area() . "</br>";
echo "Circumference: " . $circle-
>get_Circumference() . "</br>";
echo "Area: " . $circle1->get_Area() . "</br>";
echo "Circumference: " . $circle1-
>get_Circumference() . "</br>";
?>
Explanation:
In the above example code, a class Circle is defined with
Property:
public $radius;: Declares a public property called radius.
Methods:
function get_Area()
Defines a method called get_Area.
Calculates the area of the circle and returns the result.
function get_Circumference()
Defines a method called get_Circumference.
Calculates the circumference of the circle and returns the result.
Constructors and Destructors
function __construct($radius=5)
Defines a special method called the constructor (__construct).
Sets a default value of 5 for the radius parameter.
If you don't provide a value when creating a Circle object, the radius will be set to 5.
function __destruct()
Defines a destructor (__destruct).
$circle1 = new Circle()
Creates a new Circle object named $circle1. Since no value is provided for the radius in the constructor
call, the default value of 5 is used.
$circle = new Circle(15);: Creates another Circle object named $circle, but this time providing a value of
15 for the radius.
echo "Area: " . $circle->get_Area() . "</br>";: Calculates and displays the area of the $circle object
(radius 15) using the get_Area method.
echo "Circumference: " . $circle->get_Circumference() . "</br>";: Calculates and displays the
circumference of the $circle object using the get_Circumference method.
The same is repeated for $circle1 to display its area and circumference using the default radius of 5.
Overloading
In PHP, overloading refers to the ability to dynamically create properties and methods in an object at
runtime.
Overloading allows defining methods and properties that can be accessed as if they were declared within
the class, even though they are added dynamically.
This can be useful for creating more flexible and dynamic classes.
In PHP, method overloading is not supported in the same way as in some other programming languages
like Java or Python.
Overloading can be achieved in PHP using magic methods, which are special methods with predefined
names that are automatically invoked in certain situations.
Overloading in PHP provides means to dynamically create properties and methods. These dynamic
entities are processed via magic methods one can establish in a class for various action types.
class DynamicMethods {
// __call magic method for method overloading
public function __call($name, $arguments) {
if ($name == 'dynamicMethod') {
if (count($arguments) == 1) {
echo "Hello, ".$arguments[0]."!";
} elseif (count($arguments) == 2) {
echo "Sum of ".$arguments[0]." and
".$arguments[1]." is: ".($arguments[0] + $arguments[1]);
}
}
}
}
In the method overloading example, __call() magic method is defined to handle method calls that are not
defined in the class explicitly. Depending on the method name and number of arguments, different
behaviors are implemented dynamically.
What are magic methods in php
In PHP, magic methods are predefined methods that have special names prefixed with two underscores
(__). These methods are automatically invoked by PHP when certain actions occur within a class. They
allow you to hook into the object lifecycle or handle various operations in a more controlled manner.
Magic methods provide a powerful way to customize the behavior of PHP classes and objects, allowing
you to implement various features such as method overloading, property access control, serialization, and
more.
Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) where a class (subclass or
derived class) inherits properties and methods from another class (superclass or base class). This allows
you to create a hierarchy of classes where subclasses can reuse and extend the functionality of their parent
class.
<?php
// Parent class
class Animal {
protected $name;
protected $sound;
In the above example, we have a parent class Animal which has properties $name and $sound along with
a constructor to initialize them.
The Animal class also has a method makeSound() which outputs the sound the animal makes.
Then, we have two child classes: Dog and Cat, which inherit from the Animal class using the extends
keyword. This means they inherit the properties and methods of the Animal class.
Each child class can also have its own additional properties and methods, like wagTail() for Dog and
purr() for Cat.
When instances of Dog and Cat are created, they can access both the methods defined in their own class
(wagTail() and purr()) as well as those inherited from the Animal class (makeSound()).
Inheritance allows for code reusability and the creation of a hierarchy of classes, making the code more
organized and easier to maintain.