0% found this document useful (0 votes)
2 views19 pages

Php - III Unit

The document provides a comprehensive overview of PHP and MySQL concepts, focusing on functions, parameters, variable scope, and string manipulation. It covers topics such as user-defined functions, function parameters, and various string functions with examples. Additionally, it discusses object-oriented programming concepts, including classes, constructors, destructors, and traits.

Uploaded by

sharankumar26341
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)
2 views19 pages

Php - III Unit

The document provides a comprehensive overview of PHP and MySQL concepts, focusing on functions, parameters, variable scope, and string manipulation. It covers topics such as user-defined functions, function parameters, and various string functions with examples. Additionally, it discusses object-oriented programming concepts, including classes, constructors, destructors, and traits.

Uploaded by

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

PHP & MySQL – III UNIT

2 marks:
1. Give the syntax and example for defining a user-defined function in PHP.
Syntax: function functionName($parameter1, $parameter2, ...)
{
// function body
return $returnValue; // optional
}
Example: function greet($name)
{
echo "Hello, $name!";
}
// Calling the function
greet("John");

2. Differentiate between formal parameters and actual parameters in PHP functions.


Formal Parameters Actual Parameters
Variables declared in the function definition. Values or variables passed to the function during the call.
Act as placeholders to receive input values. Provide the actual input values used by the function.
Specified in the function declaration. Specified in the function call.
Eg: function add($x, $y) add(3, 7)

3. What is function scope in PHP?

In PHP, function scope refers to the visibility and accessibility of variables within a function. When
a variable is declared inside a function, it is said to have function scope, meaning it is only
accessible within that specific function.
Variables declared inside a function are known as local variables, and they exist only within the
function's body. They cannot be accessed from outside the function, and they are destroyed when
the function execution completes.
4. What happens if you call a PHP function with fewer arguments than declared in its
definition?
In PHP, if you call a function with fewer arguments than declared in its definition, PHP will
typically raise a warning or notice, depending on your error reporting settings. However, PHP will
still execute the function using the provided arguments, and any missing arguments will be assigned
a default value if default values are specified in the function definition. If no default value is
specified for a missing argument, PHP will assign null to that argument.
5. Describe the concept of default parameter values in PHP functions.
In PHP, default parameter values allow you to specify a default value for a function parameter in
case the caller of the function does not provide a value for that parameter. This feature provides
flexibility by allowing functions to be called with fewer arguments, with the default values being
used for any missing parameters.
Eg: function greet($name, $greeting = "Hello") {
echo "$greeting, $name!<br>";
}

greet("John"); // Uses default value for $greeting


greet("Jane", "Hi"); // Overrides default value for $greeting
6. How do you access global variables within a PHP function? Give example.
In PHP, you can access global variables within a function by using the global keyword followed by
the variable name. This allows you to access and modify global variables from within the function's
scope.
Eg: $globalVar = "I am a global variable";
function accessGlobal()
{
global $globalVar;
echo "Accessing global variable: $globalVar<br>";
}
accessGlobal(); // Call the function

7. What is “pass by value" in the context of PHP function parameters.


In PHP, when you pass a variable to a function as an argument, it is typically passed by value by
default. Passing by value means that a copy of the variable's value is created and passed to the
function. Any changes made to the variable within the function scope do not affect the original
variable outside of the function.
8. What is "pass by reference" in PHP function parameters?
In PHP, passing by reference allows you to pass a reference to a variable to a function, rather than a
copy of its value. This means that any changes made to the variable within the function will directly
affect the original variable outside of the function. To pass a variable by reference in PHP, you
prepend an ampersand (&) to the parameter in the function declaration.
9. What is Default Parameter in PHP functions? Give example.
Refer Q.No. 6
10. How to check missing parameters in PHP functions ? Give example.
In PHP, you can check if a parameter is missing in a function by using the func_num_args()
function to get the number of arguments passed to the function and the func_get_args() function to
get an array of all the arguments passed.
Eg: <?php
function myFunction($p1, $p2, $p3) {
$numArgs = func_num_args();
if ($numArgs < 3) {
echo "Error: Missing parameter(s)";
return;
}
$args=func_get_args(); // Get all the arguments passed to the function
print_r($args);
}
myFunction(1, 2, 3);
myFunction(1, 2);

11. What are anonymous functions? Give examples.


Anonymous functions do not have a specific name and can be defined inline or assigned to
variables. They are particularly useful for situations where you need to define a small, self-
contained function without the need for a formal declaration.
Eg: $addition = function($a, $b)
{
return $a + $b;
};
echo $addition(2, 3); // Output: 5
12. Differentiate single quoted and double quoted strings in PHP.
In single quoted strings, escape sequences like \n, \t, and \\ are not interpreted. They are treated
literally. It does not support Variable interpolation (substituting variables directly into the string). If
you use a variable inside single quotes, it will be treated as the variable name itself, not its value.
In double quoted strings, escape sequences like \n, \t, and \\ are not interpreted and replaced with
their actual characters. It supports Variable interpolation. Variables are replaced with their values
within the string.
13. What is variable interpolation? Give example.
Variable interpolation refers to the process of inserting the value of a variable directly into a string.
In PHP, this occurs when using double quoted strings, where variables enclosed in curly braces {}
or directly placed within the string are replaced with their actual values.
Example: $name = 'John';
echo "Hello, $name!"; //Output: Hello, John!
$age = 30;
echo "I am {$age} years old."; //Output: I am 30 years old.

14. Explain the two ways to interpolate variables into strings?


Double Quotes(“ ”): When you enclose a string within double quotes, PHP parses variables and
special characters inside the string.
Curly Brace { } Syntax: This method is useful when you want to clearly delimit the variable name
from surrounding text, or when accessing array elements or object properties within a string.
15. What are Here Documents in PHP? Give example.
Here documents, often referred to as heredocs, are a convenient way to declare large blocks of text
in PHP without the need for escaping special characters or using concatenation. They are especially
useful when dealing with multi-line strings or embedding HTML, SQL queries, within PHP code.
The <<< identifier token tells the PHP parser that you’re writing a heredoc.
Eg: <?php
$name = 'John';
$message = <<<EOD
Hello $name,
This is a heredoc string.
It can span multiple lines.
EOD;

16. Differentiate echo and print statements in PHP.


echo print
Does not require parentheses to be used Must be followed by parentheses
Takes multiple parameters Takes only one argument
Does not return a value Returns 1
Example: echo "Hello", " ", "World"; print("Hello World");

17. What is use of print_r() statement ? Give example.


The print_r() function in PHP is used to print human-readable information about a variable, such as
its type and structure. It is particularly useful for debugging purposes when you want to inspect the
contents of arrays, objects, or other complex data types.
Eg: $array = array('apple', 'banana'); Output: Array
print_r($array); (
[0] => apple
[1] => banana
)
18. What is type specifiers? list the printf type specifiers?
Type specifiers are placeholders used in the printf() function to specify the type of data to be
formatted and printed. They determine how the corresponding arguments are formatted in the
output string.
%s: Format as a string.
%d: Format as a signed decimal integer.
%f: Format as a floating-point number.
%c: Format as a character (ASCII value or character itself).
%b: Format as a binary number.
19. What is use of var_dump() statement ? Give example.
The var_dump() function in PHP is used to display structured information (type and value) about
one or more variables, including their data type and value. It's commonly used for debugging
purposes to inspect the contents of variables, especially complex data structures like arrays and
objects.
Example: <?php
$array = array('a', 'b');
var_dump($array);
?>
Output: array(2)
{
[0]=> string(1) "a"
[1]=> string(1) "b"
}

20. Explain trim function in php along with its types?


In PHP, the trim() function is used to remove whitespace or other specified characters from the
beginning and end of a string. It's commonly used to clean up user input, such as form submissions,
where leading or trailing whitespace can be inadvertently included. Types:
• trim(): Removes whitespace (or other specified characters) from the beginning and end of a string.
• ltrim(): Removes whitespace (or other specified characters) from the beginning (left)of a string.
• rtrim(): Removes whitespace (or other specified characters) from the end (right) of a string.
21. How can you include one PHP file into another PHP file?
In PHP, you can include the contents of one PHP file into another PHP file using the include or
require statements. These statements allow you to reuse code from one file in multiple files,
improving code organization and maintainability.
22. Name three commonly used PHP string manipulation functions.
strlen(): This function is used to get the length of a string.
strpos(): It is used to find the position of the first occurrence of a substring in a string.
substr(): This function is used to extract a substring from a string.
23. Explain strcasecmp() with example?
The strcasecmp() function in PHP is used to perform a case-insensitive string comparison. It
compares two strings and returns 0 if they are equal (ignoring case), a negative value if the first
string is less than the second, and a positive value if the first string is greater than the second.
Eg: <?php $string1 = "Hello";
$string2 = "hello";
$result = strcasecmp($string1, $string2);
echo $result; //Output: 0
?>
24. Differentiate strncmp() and strncasecmp() in php?
The strncmp() function compares the first n characters of two strings. It is case-sensitive, meaning it
considers uppercase and lowercase characters as distinct.
The strncasecmp() function ignores the case of the characters, treating uppercase and lowercase
characters as equal.
25. Write the syntax of substr_count() PHP with example.
The substr_count() counts how many times a substring appears in another string.
Syntax: substr_count($haystack, $needle, $offset, $length);
Eg: $haystack = "hello, world! hello, universe!";
$needle = "hello";
$count = substr_count($haystack, $needle);
echo "Number of occurrences of 'hello' in the string: $count";

26. Write the syntax of substr_replace() PHP with example.


The substr_replace() function in PHP is used to replace a portion of a string with another string.
Syntax: substr_replace($original_string, $replacement, $start, $length);
Eg: $a = "Hello, world!";
$b = "Universe";
$start = 7;
$new_string = substr_replace($a, $b, $start);
echo $new_string; //Output: Hello, Universe!
27. What is the purpose of the substr() function in PHP? Give example.
The substr() function in PHP is used to extract a portion of a string. It returns a substring starting
from a specified position and optionally ending at another specified position within the string.
Eg: $string = "Hello, World!";
$substring = substr($string, 7);
echo $substring; // Output: World!

28. How can you concatenate strings in PHP? Give example.


In PHP, you can concatenate strings using the dot (.) operator or the compound assignment operator
(.=) Both methods allow you to combine multiple strings into a single string. Here's an example of
concatenating strings using the dot (.) operator:
$str1 = "Hello";
$str2 = "World";
$result = $str1 . ", " . $str2;
echo $result; // Output: Hello, World

29. List two PHP library function for handling date and time.
date(): This function is used to format a timestamp (or the current date and time) into a human-
readable string according to a specified format.
strtotime(): This function is used to parse a date/time string and convert it to a Unix timestamp. It
can handle a variety of date/time formats, making it useful for converting human-readable dates into
timestamps for comparison or manipulation.
30. How do you create an instance of a class in PHP? Give example.
In PHP, you create an instance of a class using the new keyword followed by the class name,
optionally followed by parentheses containing any arguments to be passed to the class constructor.
This process is called instantiation.
Eg: class Student {
public $name;
public function _ _construct($name) {
$this->name = $name;
}
}
$s1 = new Student ("John"); // Creating an instance of the Student class
31. How you access object properties in PHP ? Give example.
In PHP, you access object properties using the arrow (->) operator. This operator is used to access
properties and methods of an object.
Eg: class Student {
public $name;
public $age;
public function _ _construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
$s1 = new Student("John",15);
echo $s1->name; Output: John
echo $s1->age; Output: 15

32. Define overloading in the context of PHP classes.


Method Overloading: In PHP, method overloading refers to the ability to define multiple methods
with the same name but different numbers or types of parameters. However, unlike some other
languages like Java, PHP does not support method overloading in the traditional sense. Instead, you
can simulate method overloading using the __call() magic method. This method allows you to
intercept calls to undefined or inaccessible methods in a class and handle them dynamically.
33. What is a constructor in PHP classes? How it is declared ?
In PHP, a constructor is a special method in a class that is automatically called when an instance of
the class is created. It is used to initialize object properties or perform any other setup tasks that are
necessary before the object can be used. It is declared using the __construct() method.
Eg: <?php
class MyClass {
public function __construct($arg1,$arg2) {
// Constructor logic goes here
} } ?>
34. What is a destructor in PHP classes? How it is declared?
In PHP, a destructor is a special method in a class that is automatically called when an object is
destroyed or when its reference count drops to zero. It is used to perform any cleanup tasks. A
destructor method in PHP is declared using the __destruct() method.
Eg: <?php
class MyClass {
public function __destruct() {
// Destructor logic goes here
} } ?>
35. How do you access object properties and methods within a class in PHP? Give example.
Within a PHP class, you can access object properties and methods using the $this keyword. The
$this keyword refers to the current object instance, allowing you to access its properties and
methods from within the class.
Eg: class MyClass {
public $property = "Hello";
public function method() {
echo $this->property;
}
}
$obj = new MyClass();
// Accessing object property
echo $obj->property; // Output: Hello
// Accessing object method
$obj->method(); // Output: Hello
36. What is a trait in PHP, and how does it differ from classes and interfaces?
In PHP, a trait is a mechanism for code reuse that allows developers to create reusable pieces of
code that can be used in multiple classes.
Traits cannot be instantiated on their own, unlike classes. They are designed to be included within
classes using the use keyword. Unlike interfaces, traits can contain method implementations. This
means that traits can provide concrete method implementations that can be reused by classes.
37. What is introspection in PHP ?
In PHP, introspection refers to the ability of a program to examine its own structure, types, and
properties at runtime. It allows developers to inspect classes, objects, functions, and other elements
of the code dynamically, without needing to know their details beforehand.

Long Answer Questions


1. Explain the steps involved in defining and invoking a user-defined function in PHP. Provide
a code example to illustrate.
i. Define the Function: To define a user-defined function in PHP, you use the function keyword
followed by the function name and parentheses. If the function takes parameters, they are listed
within the parentheses. The function body is enclosed within curly braces {}.
ii. Invoke the Function: To invoke or call a user-defined function, you simply use its name
followed by parentheses. If the function takes parameters, you pass them inside the parentheses.
Eg: <?php
// Step 1: Define the function
function greet($name)
{
echo "Hello, $name!";
}
// Step 2: Invoke the function
greet("John"); // Output: Hello, John!
?>
2. Explain the concept of variable scope in PHP functions. Explain the difference between
local, global, and static variables within the context of functions. Provide examples to
illustrate each type.
Variable scope in PHP functions refers to the visibility and accessibility of variables within different
parts of a PHP script, particularly within functions. They are of three types:
Local Variables: Local variables are declared inside a function and can only be accessed within
that function. They are not accessible outside of the function.
Eg: <?php function myFunction() {
$localVar = 10; // Local variable
echo $localVar; // Output: 10
}
myFunction();
echo $localVar; // Error: Undefined variable $localVar
?>

Global Variables: Global variables are declared outside of any function and can be accessed from
any part of the PHP script, including within functions. To access a global variable from within a
function, you need to use the global keyword or the $GLOBALS array.
Eg: <?php $globalVar = 20; // Global variable
function myFunction() {
global $globalVar;
echo $globalVar; // Output: 20
}
myFunction();
?>

Static Variables: Static variables are declared within a function like local variables, but their values
persist across multiple function calls. Static variables are initialized only once when the function is
first called.
Eg: <?php function myFunction() {
static $staticVar = 0; // Static variable
echo $staticVar;
$static Var++; // Increment the static variable
}
myFunction(); // Output: 0
myFunction(); // Output: 1
myFunction(); // Output: 2
?>

3. Explain date and time manipulation functions in PHP's standard library. Provide example
for each.
1. date(): This function formats a local date and time according to a specified format.
// Example: Display current date in 'Y-m-d' format
echo date('Y-m-d'); // Output: 2024-05-09
2. time(): This function returns the current Unix timestamp.
// Example: Get the current Unix timestamp
echo time(); // Output: 1738597025 (the current timestamp)
3. strtotime(): This function parses any English textual datetime description into a Unix timestamp.
$timestamp = strtotime('next Sunday');
echo date('Y-m-d', $timestamp); // Output: 2024-05-12 (next Sunday's date)
4. date_create(): This function creates a new DateTime object.
// Example: Create a DateTime object for the current date and time
$date = date_create():
echo $date->format('Y-m-d H:i:s); // Output: Current date and time in 'Y-m-d H:i:s' format
5. DateTime::format(): This method formats a DateTime object according to a specified format.
// Example: Format a DateTime object
$date = new DateTime('2024-05-09 14:30:00');
echo $date->format('Y-m-d H:i:s'); // Output: 2024-05-09 14:30:00
6. DateTime::modify(): This method modifies the timestamp of a DateTime object.
// Example: Modify a DateTime object
$date = new DateTime('2024-05-09');
$date->modify('+1 day');
echo $date->format('Y-m-d'); // Output: 2024-05-10
4. Explain Passing parameter by value and by reference with respect to PHP functions. Give
example for each.
Passing Parameters by Value: When you pass parameters by value, a copy of the variable's value
is passed to the function. Any changes made to the parameter inside the function do not affect the
original variable outside the function. By default, PHP passes parameters by value.
Eg: <?php
function increment($num) {
$num++; // Increment the value of $num
echo $num; // Output: 6
}
$number = 5;
increment($number);
echo $number; // Output: 5 (unchanged)
?>
In this example, $number remains unchanged after calling the increment() function because the
parameter $num is passed by value.
Passing Parameters by Reference: When you pass parameters by reference, you pass a reference
to the variable itself rather than a copy of its value. Any changes made to the parameter inside the
function affect the original variable outside the function.
To pass a parameter by reference, you use the & symbol before the parameter name in both the
function declaration and the function call.
Eg: <?php
function incrementByReference(&$num) {
$num++; // Increment the value of $num
echo $num; // Output: 6
}
$number = 5;
incrementByReference($number);
echo $number; // Output: 6 (changed)
?>
In this example, $number is incremented by 1 after calling the incrementByReference() function
because the parameter $num is passed by reference.
5. Explain type hinting in php with example?
Type hinting in PHP allows you to specify the data type of parameters and return values for
functions and methods. It helps in enforcing stricter type checks and improves code readability and
reliability. There are two types of type hinting available in PHP:
Parameter Type Hinting: Specifies the data type of a parameter that a function or method expects.
Eg: <?php function calculateSum(array $numbers) {
$sum = 0;
foreach ($numbers as $num) {
$sum += $num;
}
return $sum;
}
$numbers = [1, 2, 3, 4, 5];
echo calculateSum($numbers); // Output: 15
In this example, array $numbers specifies that the parameter $numbers must be an array.
Return Type Hinting: Specifies the data type that a function or method will return.
Eg: <?php function calculateAverage(array $numbers): float {
$count = count($numbers);
if ($count === 0) {
return 0.0;
}
$sum = array_sum($numbers);
return $sum / $count;
}
$numbers = [1, 2, 3, 4, 5];
echo calculateAverage($numbers); // Output: 3.0
In this example, float specifies that the function calculateAverage will return a float (floating-point
number).
6. Write a note on
i) Variable functions ii) Function with default argument iii) Function with variable argument
i. Variable Functions: Variable functions allows a variable to be used as the name of a function.
This means that you can assign a function name to a variable and then invoke the function through
that variable.
Eg: <?php function sayHello($name) {
echo "Hello, $name!";
}
$functionName = "sayHello"; // Assign function name to a variable
// Call the function using the variable
$functionName("John"); // Output: Hello, John!
?>

ii) Function with Default Argument: In PHP, you can define default values for function
parameters. If a default value is specified for a parameter and no value is passed for that parameter
when the function is called, the default value will be used. This allows functions to have optional
parameters.
Eg: <?php function greet($name = "World") {
echo "Hello, $name!";
}
greet(); // Output: Hello, World!
greet("John"); // Output: Hello, John!
?>

iii) Function with Variable Argument: PHP supports variable-length argument lists in functions,
which means you can define functions that accept a variable number of arguments.
PHP provides three functions you can use in the function to retrieve the parameters passed to it.
func_get_args() returns an array of all parameters provided to the function;
func_num_args() returns the number of parameters provided to the function;
func_get_arg() returns a specific argument from the parameters.
Example: <?php function countList()
{
if (func_num_args() == 0)
{
echo “no arguments passed”;
} else {
for ($i = 0; $i < func_num_args(); $i++)
{
echo func_get_arg($i);
}
}
}
countList(); // no arguments passed
countList(1,2,3); // 1 2 3
countList(1,2,3,4,5); // 1 2 3 4 5
?>

7. Write a note on anonymous functions in PHP.


Anonymous functions do not have a specific name and can be defined inline or assigned to
variables. They are particularly useful for situations where you need to define a small, self-
contained function without the need for a formal declaration such as callbacks for array functions,
event handling, or arguments to other functions.
Syntax: $anonymousFunction = function($arg1, $arg2, ...)
{
// Function body
};
Eg: // Define and use an anonymous function
$sum = function($a, $b)
{
return $a + $b;
};
echo $sum(2, 3);

8. Describe how strings are declared and initialized in PHP. Explain the difference between
single quotes ('') and double quotes ("") in string declaration with example.
In PHP, strings are sequences of characters, such as letters, numbers, and symbols, enclosed within
either single quotes ('') or double quotes (""). Here's how strings are declared and initialized:
Single Quotes (' '):
• Special characters (except ') are treated literally.
• Variables are not expanded; they are treated as literals.
• Slightly faster than double quotes because PHP doesn't need to parse the string for variable
interpolation.
Eg: $name = 'John';
$string1 = 'Hello, $name'; // Output: Hello, $name
Double Quotes (" "):
• Special characters are interpreted (e.g., \n, \t).
• Variables are expanded; their values are included in the string.
• Slower than single quotes because PHP needs to parse the string for variable interpolation.
Eg: $name = 'John';
$string2 = "Hello, $name"; // Output: Hello, John
9. Write note on string here document declarations.
Here documents, often referred to as heredocs, are a convenient way to declare large blocks of text
in PHP without the need for escaping special characters or using concatenation. They are especially
useful when dealing with multi-line strings or embedding HTML, SQL queries, within PHP code.
• The <<< identifier token tells the PHP parser that you’re writing a heredoc.
• Inside a heredoc, variables are interpolated just like in double-quoted strings.
• Special characters like " and ' do not need escaping.
• Heredoc content is preserved exactly as it is written, including leading whitespace.
Eg: <?php
$name = 'John';
$message = <<<EOD
Hello $name,
This is a heredoc string.
It can span multiple lines.
EOD;

<<<EOD is the heredoc identifier. It can be any arbitrary string, but EOD is commonly used. The
text block starts immediately after the <<<EOD and continues until the identifier (EOD) is repeated
at the beginning of a line, followed by a semicolon (;).
10. Explain print_r() and var_dump() functions in PHP with example.
Both print_r() and var_dump() are PHP functions used for debugging and inspecting variables. They
display information about a variable or expression in a human-readable format.
print_r():
• The print_r() function displays information about a variable in a more human-readable format. It
is particularly useful for arrays, objects, and variables with nested structures.
• It displays the value of the variable, its data type, and its structure, including keys and values for
arrays.
• It does not display the data types of the elements in an array.
Example:
<?php
$array = array('a', 'b');
print_r($array);
?>

Output:
Array
(
[0] => a
[1] => b
)
var_dump():
• The var_dump() function provides more detailed information about a variable or expression,
including its data type and value.
• It displays the data type of each element in an array or object, making it useful for debugging and
understanding variable types.
• It also displays the length of strings and the number of elements in arrays and objects.
Example: <?php
$array = array('a', 'b');
var_dump($array);
?>
Output: array(2)
{
[0]=> string(1) "a"
[1]=> string(1) "b"
}

In the example above, print_r() provides a more concise view of the array's structure, while
var_dump() provides additional information such as the data type and length of each element.
11. Explain any four string functions in PHP with example.
i. strlen(): Returns the length of a string.
Example: <?php
$string = "Hello, world!";
$length = strlen($string);
echo "Length of the string: $length"; //O/p: Length of the string:13
?>

ii. strtolower(): Converts a string to lowercase.


Example: <?php
$string = "Hello, World";
$lowercase = strtolower($string);
echo $lowercase; // Output: hello, world!
?>

iii. strtoupper(): Converts a string to uppercase.


Example: <?php
$string = "Hello, World!";
$uppercase = strtoupper($string);
echo $uppercase; // Output: HELLO, WORLD!
?>

iv. substr(): Returns a part of a string specified by a start position and length.
Example: <?php
$string = "Hello, world!";
$substring = substr($string, 7, 5);
echo $substring; // Output: world
?>

12. Explain miscellaneous string functions in PHP with examples.


i. strrev(): This function takes a string and returns a reversed copy of it.
Syntax: strrev(string);
Eg: <?php echo strrev("There is no cabal"); ?> // Output : labac on si erehT
ii. str_repeat(): This function takes a string and a count and returns a new string consisting of the
argument string repeated count times.
Syntax: str_repeat(string, count);
Eg: <?php echo str_repeat("Enhypen",3); ?> //Output: EnhypenEnhypenEnhypen

iii. str_pad(): This function pads one string with another. Optionally, you can say what string to pad
with, and whether to pad on the left, right, or both. Default is a space (" ").
Syntax: str_pad(to_pad, length [, with [, pad_type ]]);
Eg: <?php $str = "Hello";
$padded_str = str_pad($str, 10, ".", STR_PAD_LEFT);
echo $padded_str;
?> //Output: .....Hello

iv. trim(): This function removes whitespace or other predefined characters from both the
beginning and end of a string.
Syntax: trim(string,charlist)
Eg: <?php $string = " Hello, world! ";
$trimmed_string = trim($string);
echo $trimmed_string; // Output: Hello, world!
?>

13. Explain the functions used in PHP to test whether two Strings are approximately equal.
levenshtein() : The levenshtein() function calculates the similarity of two strings based on how
many characters you must add, substitute, or remove to make them the same. A lower Levenshtein
distance indicates higher similarity.
Eg: <?php echo levenshtein("cat", "cot"); ?> // Output: 1
similar_text(): The similar_text() function returns the number of characters that its two string ar
guments have in common. The third argument, if present, is a variable in which to store the
commonality as a percentage.
Eg: <?php $string1 = "hello";
$string2 = "hallo";
similar_text($string1, $string2, $similarity);
echo $similarity; //Output: 80
?>

soundex(): The soundex() function in PHP calculates the soundex key of a string, which can be
used to compare the sounds of two strings rather than their exact spelling. This can be useful for
approximate string matching based on pronunciation.
Eg: <?php $str1 = soundex("robert");
$str2 = soundex("rupert");
echo $ str1 == $ str2 ? 'True' : 'False'; // Outputs: true
?>

metaphone(): The metaphone() function calculates the metaphone key of a string, which is a
phonetic algorithm for indexing words by their sound when pronounced in English. This can be
useful for comparing the similarity of words phonetically. metaphone() is generally more accurate.
Eg: <?php $meta1 = metaphone("knight");
$meta2 = metaphone("night");
echo $meta1 == $meta2 ? 'True' : 'False'; // Outputs: True
?>
14. Explain explode() and strtok() functions with respect to PHP strings.
The explode() function splits a string into an array of substrings based on a specified delimiter.
Syntax: $array = explode(separator, string [, limit]);
The argument separator, is a string containing the field separator. string, is the string to split. The
optional third argument, limit, is the maximum number of values to return in the array. If the limit is
reached, the last element of the array contains the remainder of the string.
Eg: <?php $string = "apple,banana,orange";
$fruits = explode(",", $string);
print_r($fruits); // Output: Array ( [0]=>apple [1]=>banana [2]=>orange )
?>

The strtok() function lets you iterate through a string, getting a new chunk (token) each time. It
returns false when there are no more tokens to be returned. The first time you call it, you need to
pass two arguments: the string to iterate over and the token separator. For example:
$firstChunk = strtok(string, separator);
To retrieve the rest of the tokens, repeatedly call strtok() with only the separator:
$nextChunk = strtok(separator);
Eg: $string = "Fred,35,Wilma";
$token = strtok($string, ",");
while ($token !== false) {
echo $token."\n";
$token = strtok(",");
}
Output: Fred
35
Wilma

15. Explain the process of creating a class and instantiating objects in PHP with code example.
Creating a class in PHP involves defining a blueprint for objects, including properties (variables)
and methods (functions) that describe the behavior and data associated with those objects. To define
a class in PHP, you use the class keyword followed by the name of the class.
Once the class is defined, you can instantiate objects from it, which are instances of that class. To
create an object of a class, you use the new keyword followed by the class name, and assign it to a
variable. We can access the properties and methods of the objects using the object operator (->).
Eg: <?php class MyClass // Define a class
{
public $name; // Properties (variables)
public $age;
public function __construct($name, $age) // Constructor method
{
$this->name = $name;
$this->age = $age;
}
public function greet() { // Method
echo "Hello my name is {$this->name} and I am {$this->age} years old.";
}
}
// Instantiate objects from the class
$object1 = new MyClass("John", 30);
$object2 = new MyClass("Alice", 25);
// Access object properties and methods
echo $object1->name; // Output: John
echo $object2->age; // Output: 25
$object1->greet(); //Output: Hello, my name is John and I am 30 years old.
$object2->greet(); //Output: Hello, my name is Alice and I am 25 years old.
?>
16. Explain the concept of inheritance in PHP classes with example.
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class
(called a subclass or derived class) to inherit properties and methods from another class (called a
superclass or base class). Inheritance enables code reuse and promotes a hierarchical structure
where subclasses can extend and specialize the behavior of their parent classes.
Eg: <?php // Define a superclass
class Animal {
// Properties
public $name;
public $age;
public function __construct($name, $age) { // Constructor
$this->name = $name;
$this->age = $age;
}
public function greet() { // Method
return "Hello, my name is {$this->name} and I am {$this->age} years old.";
}
}
// Define a subclass that inherits from the superclass
class Dog extends Animal {
// Additional property specific to Dog
public $breed;
public function __construct($name, $age, $breed) { // Constructor
// Call superclass constructor
parent::__construct($name, $age);
$this->breed = $breed;
}
// Additional method specific to Dog
public function bark() {
return "Woof!";
}
}
// Instantiate objects
$animal = new Animal("Generic Animal", 5);
$dog = new Dog("Buddy", 3, "Labrador");
// Access properties and methods
echo $animal->greet(); // Output: Hello, my name is Generic Animal and I am 5 years old.
echo $dog->greet(); // Output: Hello, my name is Buddy and I am 3 years old.
echo $dog->bark(); // Output: Woof!
?>
17. Explain the role of access modifiers in PHP classes, such as public, private, and protected.
Access modifiers in PHP classes are keywords used to control the visibility of properties and
methods within a class hierarchy. They specify how properties and methods can be accessed from
outside the class or from subclasses. PHP supports three access modifiers:
public: Properties and methods declared as public are accessible from outside the class as well as
from within the class and its subclasses. They have no restrictions on access.
Eg: <?php class MyClass {
public $publicProperty;
public function publicMethod() {
// Method implementation
}
}
$obj = new MyClass();
$obj->publicProperty = "Hello"; // Accessing public property
$obj->publicMethod(); // Accessing public method
?>
private: Properties and methods declared as private are only accessible from within the class itself.
They cannot be accessed from outside the class or from its subclasses.
Eg: <?php class MyClass {
private $privateProperty;
private function privateMethod() {
// Method implementation
}
}
$obj = new MyClass();
$obj->privateProperty = "Hello"; // Error: Cannot access private property
$obj->privateMethod(); // Error: Cannot access private method
?>
protected: Allows properties and methods to be accessed within the class itself and by its
subclasses. They cannot be accessed from outside the class hierarchy.
Eg: <?php class MyClass {
protected $protectedProperty;
protected function protectedMethod() {
// Method implementation
}
}
class SubClass extends MyClass {
public function accessProtected() {
$this->protectedProperty = "Hello"; // Accessing protected property from
subclass
$this->protectedMethod(); // Accessing protected method from subclass
}}
$obj = new SubClass();
$obj->accessProtected(); // Accessing protected members from subclass
?>
18. Explain the process of implementing an interface in PHP with code example.
In PHP, implementing an interface involves creating a class that defines the methods specified by
the interface. The class then implements those methods, providing their concrete implementations.
Interfaces are declared using the interface keyword. Next, you create a class that implements the
interface using the implements keyword. This class must provide implementations for all the
methods declared in the interface.
Eg: <?php
interface Interface1 {
public function display();
}
class A implements Interface1 {
public function display() {
echo "Class A implementation of interface method display() <br>";
}
}
class B implements Interface1 {
public function display() {
echo " Class B implementation of interface method display()";
}
}
$a1 = new A();
$b1 = new b();
$a1->display();
$b1->display();
?>
Output: Class A implementation of interface method display()
Class B implementation of interface method display()
19. Explain how traits are used in PHP classes with example program.
In PHP, a trait is a mechanism for code reuse that allows developers to create reusable pieces of
code that can be used in multiple classes.
Traits can have methods and abstract methods that can be used in multiple classes, and the methods
can have any access modifier (public, private, or protected).
• You define a trait using the trait keyword followed by the trait name. Inside the trait, you can
declare methods just like you would in a regular class.
• To use a trait in a class, you use the use keyword followed by the trait name inside the class
definition.
• You can now create objects of the class and call the methods defined in both the class and the trait.
Syntax:
Eg: <?php trait message1 {
public function msg1() {
echo "OOP is fun! ";
}}
trait message2 {
public function msg2() {
echo "OOP reduces code duplication!";
}}
class Welcome {
use message1;
}
class Welcome2 {
use message1, message2;
}
$obj = new Welcome();
$obj->msg1();
echo "<br>";
$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2();
?>
Output: OOP is fun!
OOP is fun! OOP reduces code duplication!
20. Explain conflict resolution during multiple trait usage in PHP class with code example.
When using multiple traits in a PHP class, conflicts may arise if two or more traits provide methods
with the same name. PHP provides a mechanism for resolving such conflicts by using the insteadof
and as operators.
insteadof : This operator is used to explicitly choose which method to use when there is a conflict
between methods from multiple traits.
as: This operator is used to give an alias to a method from a trait, allowing access to it under a
different name even if it is not used in the conflict resolution.
Eg: <?php trait Loggable {
public function log() {
echo " Loggable log method";
}
}
trait Debuggable {
public function log() {
echo "Debuggable log method";
}
}
class User {
use Loggable, Debuggable {
Loggable::log insteadof Debuggable;
Debuggable::log as debugLog;
}
}
$user = new User(); // creating object
$user->log(); // this invokes Loggable trait’s log() method
$user->debugLog(); // this invokes Debuggable trait’s log() method
?>

You might also like