0% found this document useful (0 votes)
20 views43 pages

WBP QB Answers $F

The document is a question bank for PHP programming, covering various topics such as advantages of PHP, syntax, loops, decision-making statements, data types, arrays, functions, and constants. It includes examples and explanations for each concept, along with code snippets to illustrate usage. The document serves as a study guide for understanding PHP fundamentals and programming techniques.

Uploaded by

khantaukirhasan
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)
20 views43 pages

WBP QB Answers $F

The document is a question bank for PHP programming, covering various topics such as advantages of PHP, syntax, loops, decision-making statements, data types, arrays, functions, and constants. It includes examples and explanations for each concept, along with code snippets to illustrate usage. The document serves as a study guide for understanding PHP fundamentals and programming techniques.

Uploaded by

khantaukirhasan
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/ 43

Faizan.

WBP QUESTION BANK (PTT1)

CHP 1 (2 MARKS):

1. Describe advantage of PHP


ANS:

1. Open Source and Free of Cost:


People can download it from an open source and get it for free.

2. Platform Independence:
PHP-based applications can run on any OS such as UNIX, Windows,
Linux, etc.

3. Database Connection:
It has a built-in database connection that helps to connect databases
and reduce the trouble and the time to develop web applications or
content-based sites altogether.

4. Library Support:
PHP has strong library support, which allows utilizing various function
modules for data representation.

2. Write syntax of PHP.


ANS:
A PHP script starts with the tag <?php and ends with the tag ?>.
Example:

php

<?php

echo "Hello World";

?>

3. List any four advantages of PHP.


ANS:

1. Open Source and Free of Cost:


People can download it from an open source and get it for free.
Faizan.M

2. Platform Independence:
PHP-based applications can run on any OS such as UNIX, Windows,
Linux, etc.

3. Database Connection:
It has a built-in database connection that helps to connect databases.

4. Library Support:
PHP has strong library support using which one can utilize various
function modules for data representation.

4. Write a program using Foreach loop.


ANS:

php

<?php

// Array of fruits

$fruits = array("Apple", "Banana", "Cherry", "Date");

// Using foreach loop to iterate through the array

foreach ($fruits as $fruit) {

echo $fruit . "<br>";

?>

5. State any 2 differences between for and foreach.


ANS:

o For Loop is used to execute a set of statements multiple times using a


variable, condition, and increment/decrement, while foreach loop is
used to traverse through values in an array.

o For Loop is used to execute a set of statements multiple times,


whereas foreach loop is specifically for arrays.
Faizan.M

6. State the use of $ sign in PHP.


ANS:
The $ sign in PHP is used to indicate a variable. A variable starts with the $
sign, followed by the name of the variable.
Example:

php

$a = 10;

CHP 1 (4/6 MARKS):

1. Explain different loops in PHP.


ANS:

1. While Loop:
If the expression/condition specified with while evaluates to true, the
statements inside the loop execute, and control is transferred back to the
expression/condition.

Example:

php

<?php

$a = 1;

while ($a <= 5) {

echo "Iteration $a <br>";

$a++;

?>

OR

php

<?php

$a = 1;
Faizan.M

while ($a <= 5):

echo "Iteration $a <br>";

$a++;

endwhile;

?>

2. Do-While Loop:
All the statements inside the loop execute for the first time without
checking any condition. The keyword do passes the flow of control inside
the loop. After executing the loop for the first time, the
expression/condition is evaluated. If it evaluates to true, all statements
inside the loop execute again; otherwise, the loop exits.

Example:

php

<?php

$a = 1;

do {

echo "Iteration $a <br>";

$a++;

} while ($a <= 5);

?>

3. For Loop:
The for loop is used when the number of iterations is known in advance.

Example:

php

<?php

for ($i = 0; $i < 5; $i++) {

echo "Iteration $i <br>";

}
Faizan.M

?>

4. Foreach Loop:
The foreach loop is specifically used for arrays to iterate over each
element.

Example:

php

<?php

$colors = array("Red", "Green", "Blue");

foreach ($colors as $color) {

echo $color . "<br>";

?>

2. Explain decision-making statements along with their syntax in PHP.


ANS:
If-Else Control Statement is used to check whether a condition/expression is
true or false. If the expression/condition evaluates to true, the code block
associated with if is executed; otherwise, the code block associated with else is
executed.

Syntax:

php

if (expression/condition) {

// True code block

} else {

// False code block

Example:

php
Faizan.M

<?php

$a = 30;

if ($a < 20)

echo "Variable value a is less than 20";

else

echo "Variable value a is greater than 20";

?>

In the above example, the variable $a holds the value 30. The condition checks whether
$a is less than 20. Since it evaluates to false, the output displays: "Variable value a is
greater than 20."

3. Explain the use of break and continue statements.


ANS:

1. Break Statement:
The break keyword is used to terminate and transfer the control to the
next statement when encountered inside a loop or switch case
statement.

Syntax:

php

if (condition) {

break;

Example:

php

<?php

for ($a = 0; $a < 10; $a++) {

if ($a == 7) {
Faizan.M

break; // Break the loop when condition is true

echo "Number: $a <br>";

echo "Terminated the loop at $a number";

?>

2. Continue Statement:
The continue keyword skips the execution of a particular statement
inside the loop and proceeds with the next iteration.

Example:

php

<?php

for ($i = 0; $i < 10; $i++) {

if ($i == 5) {

continue; // Skip iteration when $i is 5

echo "Number: $i <br>";

?>

4. List loop control structures. Explain any one loop control structure.
ANS:

Loop Control Structures:

o While Loop

o Do-While Loop

o For Loop

o Foreach Loop

While Loop Example:


Faizan.M

php

<?php

$a = 1;

while ($a <= 5) {

echo "Iteration $a <br>";

$a++;

?>

5. Write a program using do-while loop.


ANS:

php

<?php

$n = 1;

do {

echo "$n<br/>";

$n++;

} while ($n <= 10);

?>

6. Implement any three data types used in PHP with illustration.


ANS:
PHP provides eight types of values or data types:

o Four are scalar (single-value) types: integers, floating-point numbers,


strings, and Booleans.

o Two are compound (collection) types: arrays and objects.

o Two are special types: resource and NULL.


Faizan.M

4. Integers:
Integers are whole numbers, such as 1, 12, and 256. Integer literals can be written in
decimal, octal, or hexadecimal.
Example:

php

// Decimal, Octal, and Hexadecimal

$decimal = 1998;

$octal = 0755; // decimal 493

$hex = 0xFF; // decimal 255

$binary = 0b0110; // binary format (decimal 6)

5. Floating-Point Numbers:
Represent numeric values with decimal digits. They can be written in general format or
scientific format.
Example:

php

$general = 3.14;

$scientific = 0.314E1; // Equivalent to 3.14

6. Strings:
A string is a sequence of characters, enclosed in either single or double quotes.
Example:

php

$str = "Hello, PHP!";

$rollNo = 10;

echo "My roll number is $rollNo";

7. Booleans:
Represent true (1) or false (0) values, commonly used in conditional testing.
Example:

php
Faizan.M

$isAvailable = true;

if ($isAvailable) {

echo "Available";

8. Arrays:
Arrays hold multiple values, accessed using either numeric or string keys.
Example:

php

$colors = array("Red", "Green", "Blue"); // Indexed array

$student = array("Maths" => 95, "Physics" => 90); // Associative array

7. Write down rules for declaring PHP variable.


ANS:
a. A variable starts with the $ sign, followed by the variable name.
b. A variable name must start with a letter or an underscore.
c. A variable name cannot start with a number.
d. A variable name can only contain alphanumeric characters and
underscores.
e. Variable names are case-sensitive ($name and $NAME are two different
variables).
f. Variables do not have intrinsic types; PHP automatically converts them to the
correct type based on the value assigned.
Example:

php

$firstName = "John"; // String

$age = 25; // Integer

8. Explain different loops in PHP with example.


ANS:
Same as Question 1.
Faizan.M

9. Explain constant with example.


ANS:
In PHP, constants are identifiers that hold a single value. Unlike variables, the
value of a constant cannot be changed during the script's execution. They are
typically defined using the define() function or the const keyword.

Example:

php

<?php

// Defining a constant using define()

define("SITE_NAME", "MyWebsite");

// Defining a constant using const

const PI = 3.14159;

// Displaying constant values

echo SITE_NAME . "<br>";

echo "Value of PI: " . PI;

?>

10. Explain the following terms: (i) Variables (ii) Datatypes (iii) Constant (iv)
Operators
ANS:
(i) Variables: Containers for storing data values. In PHP, a variable starts with a $
sign, followed by the variable name.

(ii) Datatypes: Classifications that specify the type of value a variable can hold.
Examples: integers, floating-point numbers, strings, Booleans, arrays, objects,
resources, NULL.

(iii) Constant: An identifier that holds a single value which cannot be changed during
script execution.
Faizan.M

(iv) Operators: Symbols used to perform operations on variables and values. Examples:
Arithmetic operators (+, -, *), comparison operators (==, >), logical operators (&&, ||).

CHP 2 (2 MARKS):

1. State the use of str_word_count() along with its syntax.


ANS:
The str_word_count() function is used to count the number of words in a
string.

Syntax:

php

str_word_count(string, return, char);

o string: The string to be checked.

o return: Optional. Specifies the return value.

 0: Returns the number of words found.

 1: Returns an array with the words from the string.

 2: Returns an array where the key is the position of the word in the
string, and the value is the actual word.

o char: Optional. Specifies special characters to be considered as words.

Example:

php

<?php

$str1 = "Welcome to WBP Theory & Practical";

echo "Total words in string str1: " . str_word_count($str1, 0, "&");

?>

2. List different types of arrays.


ANS:

o Indexed Arrays
Faizan.M

o Associative Arrays

o Multidimensional Arrays

3. Explain class and object creation.


ANS:
A class is defined 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 curly
brackets.

Syntax:

php

class classname [extends baseclass][implements interfacename, ...]

[visibility $property [= value]; ...]

[function functionname(args) { code } ...] // Method declaration & definition

Object: An object is an instance of a class. The data associated with an object are
called its properties, and the functions associated with an object are called its
methods. Objects are created using the new keyword.

Syntax:

php

$object = new classname();

Example:

php

<?php

class student {

public $name;

public $rollno;
Faizan.M

// Constructor to initialize properties

function __construct($name, $rollno) {

$this->name = $name;

$this->rollno = $rollno;

// Creating an object with a constructor

$s1 = new student("John", 101);

?>

4. Explain functions. List its types.


ANS:
Definition: A function is a block of code written to perform a specific task. It
takes information as parameters, executes a block of statements, and returns
the result. A function is executed by calling it.

Types of Functions in PHP:

o Default Function

o Parameterized Function

o Variable Function

o Lambda (Anonymous) Function

o Arrow Function (Short Closure)

Syntax:

php

function functionName() {

// Code to be executed

}
Faizan.M

Example:

php

<?php

function writeMsg() {

echo "Welcome to PHP World!";

// Call the function

writeMsg();

?>

5. State the use of strlen() & strrev().


ANS:

strlen() function:
This function is used to find the number of characters in a string. Spaces between
words are also counted.
Syntax:

php

strlen(string);

o string: The string whose characters are to be counted.

Example:

php

<?php

$str3 = "Hello, welcome to WBP";

echo "Number of characters in the string '$str3' = " . strlen($str3);

?>
Faizan.M

strrev() function:
This function accepts a string as an argument and returns a reversed copy of it.
Syntax:

php

$strname = strrev(string);

Example:

php

<?php

$str4 = "Polytechnic";

$str5 = strrev($str4);

echo "Original string is '$str4' and reverse of it is '$str5'";

?>

6. What is an array? How to store data in an array?


ANS:
Definition: An array is a special type of variable that can store multiple values
in a single reference, allowing efficient data management and retrieval.

Examples:

1. Indexed Array:

php

$colors = array("Red", "Green", "Blue");

2. Associative Array:

php

$student_one = array("Maths" => 95, "Physics" => 90, "Chemistry" => 96);

3. Multidimensional Array:
Faizan.M

php

$movies = array(

"comedy" => array("Pink Panther", "Johnny English"),

"action" => array("Die Hard", "Inception"),

"epic" => array("The Lord of the Rings")

);

CHP 2 (4/6 MARKS):

1. Explain Indexed & Associative Arrays with suitable examples.


ANS:

Indexed Arrays:

o In Indexed Arrays, elements are stored and accessed using numeric


indices, starting from 0.

o These arrays can store any type of element, and the index is always a
number.

Array Initialization:
First Method:

php

$colors = array("Red", "Green", "Blue");

Second Method:

php

$colors[0] = "Red";

$colors[1] = "Green";

$colors[2] = "Blue";

Example:

php
Faizan.M

<?php

$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");

// Accessing the elements directly

echo "Accessing the 1st array element directly: ";

echo $name_one[2] . "\n"; // Output: Ram

echo $name_one[0] . "\n"; // Output: Zack

echo $name_one[4] . "\n"; // Output: Raghav

?>

Associative Arrays:

o Associative Arrays store data in key-value pairs, where the key is a string
and the value can be any data type.

o These behave more like two-column tables, where the first column is the
key, and the second is the value.

Example:

php

<?php

// First method to create an associative array

$student_one = array("Maths" => 95, "Physics" => 90, "Chemistry" => 96);

// Second method to create an associative array

$student_two["Maths"] = 95;

$student_two["Physics"] = 90;

$student_two["Chemistry"] = 96;

?>

// Accessing values

<?php
Faizan.M

echo "Marks for student in Maths: " . $student_two["Maths"] . "\n";

echo "Marks for student in Physics: " . $student_two["Physics"] . "\n";

?>

2. Explain constructor with example.


ANS:

A constructor is a special built-in method that allows initializing object properties when
an object is created. It executes automatically when an object is created. The
construct method starts with two underscores (__).

Syntax:

php

function __construct([argument1, argument2, ..., argumentN]) {

// Class initialization code

Example:

php

<?php

class student {

var $name;

function __construct($name) {

$this->name = $name;

function display() {

echo $this->name;

}
Faizan.M

$s1 = new student("xyz");

$s1->display(); // Output: xyz

?>

3. Explain the following string functions with examples:


(i) str_replace() (ii) ucwords() (iii) strlen() (iv) strtoupper()
ANS:

1. str_replace() function:
This function is used to replace characters in a string with other
characters.

Syntax:

php

str_replace(findword, replace, string, count);

 findword: The word to find in the string.

 replace: The word to replace the found word.

 string: The string on which the replacement is to be performed.

 count: Optional. Indicates the number of occurrences replaced.

Example:

php

<?php

$str = "Welcome to poly";

$newStr = str_replace("poly", "MSBTE", $str);

echo $newStr; // Output: Welcome to MSBTE

?>
Faizan.M

2. ucwords() function:
This function converts the first character of each word in a string to
uppercase.

Syntax:

php

$variable = ucwords($stringvar);

Example:

php

<?php

$str = "welcome to php world";

echo ucwords($str); // Output: Welcome To Php World

?>

3. strlen() function:
This function counts the number of characters in a string, including
spaces.

Syntax:

php

strlen(string);

Example:

php

<?php

$str = "Hello, welcome to PHP";

echo "Number of characters: " . strlen($str);

?>
Faizan.M

4. strtoupper() function:
This function converts all characters in a string to uppercase.

Syntax:

php

$variable = strtoupper($stringvar);

Example:

php

<?php

$str = "polytechnic";

echo strtoupper($str); // Output: POLYTECHNIC

?>

4. Explain constructor and destructor in PHP.


ANS:

Constructor:

A constructor is a special built-in method that allows initializing object properties when
an object is created. It executes automatically when an object is created. The
__construct() method starts with two underscores (__).

Syntax:

php

function __construct([argument1, argument2, ..., argumentN]) {

// Class initialization code

Example:

php
Faizan.M

<?php

class Student {

var $name;

function __construct($name) {

$this->name = $name;

function display() {

echo $this->name;

$s1 = new Student("John Doe");

$s1->display(); // Output: John Doe

?>

Destructor:

A destructor is the counterpart of a constructor. It is called when the object is


destroyed. A destructor function cleans up any resources allocated to an object. The
__destruct() method starts with two underscores (__).

Syntax:

php

function __destruct() {

// Cleanup code

Example:

php
Faizan.M

<?php

class Student {

var $name;

function __construct($name) {

$this->name = $name;

function __destruct() {

echo "Destructor is executing for " . $this->name;

$s1 = new Student("John Doe");

?>

5. Explain the operations on string:


(i) strrev() (ii) strpos()
ANS:

1. strrev() function:
This function accepts a string and returns a reversed copy of it.

Syntax:

php

$strname = strrev(string);

Example:

php

<?php
Faizan.M

$str = "Polytechnic";

$reversedStr = strrev($str);

echo "Original string: $str <br> Reversed string: $reversedStr";

?>

2. strpos() function:
This function is used to find the position of the first occurrence of a
specified word in another string. It returns false if the word is not found. It
is case-sensitive.

Syntax:

php

strpos(string, findstring, start);

 string: The string to be searched.

 findstring: The word to find in the specified string.

 start: Optional. Specifies where to start the search. If negative, it


counts from the end.

Example:

php

<?php

$str = "Welcome to Polytechnic";

$result = strpos($str, "Poly", 0);

echo "The word 'Poly' is found at position: $result";

?>

6. Explain the procedure to create a PDF in PHP. Write an example.


ANS:

Steps to create a PDF in PHP:

1. Install FPDF Library: Download FPDF from fpdf.org and extract it into
your project folder.
Faizan.M

2. Include the FPDF File: Use require("fpdf/fpdf.php"); to load the library.

3. Create a PDF Object: Instantiate the FPDF class.

4. Add a Page: Use $pdf->addPage(); to create a new page.

5. Set Font & Style: Use $pdf->setFont(); to define the text font, style, and
size.

6. Set Text Color: Use $pdf->setTextColor(); for colored text.

7. Add Content: Use $pdf->cell(); to write text inside the PDF.

8. Output the PDF: Use $pdf->output(); to display or save the PDF.

Example:

php

<?php

require("fpdf/fpdf.php"); // Path to fpdf.php

$pdf = new FPDF();

$pdf->addPage();

$pdf->setFont("Arial", 'IBU', 16);

$pdf->setTextColor(150, 200, 225);

$pdf->cell(40, 10, "Hello Out There!");

$pdf->output();

?>

7. List string functions in PHP. Explain any two.


ANS:

Common string functions in PHP:

o str_word_count()

o strlen()

o strrev()

o strcmp()
Faizan.M

o strpos()

o str_replace()

o ucwords()

o strtoupper()

o strtolower()

1. str_word_count() function:
Used to count the number of words in a string.
Syntax:

php

str_word_count(string, return, char);

Example:

php

<?php

$str = "Welcome to WBP Theory & Practical";

echo "Total words in string: " . str_word_count($str, 0, "&");

?>

2. strlen() function:
Used to find the number of characters in a string.

Syntax:

php

strlen(string);

Example:

php

<?php

$str = "Hello, welcome to WBP";


Faizan.M

echo "Number of characters: " . strlen($str);

?>

8. Develop a PHP program to create a constructor to initialize an object of a class.

Ans:

php

<?php

class Student {

public $name;

public $rollno;

// Constructor to initialize object properties

function __construct($name, $rollno) {

$this->name = $name;

$this->rollno = $rollno;

// Function to display student details

function display() {

echo "Name: " . $this->name . "<br>";

echo "Roll No: " . $this->rollno . "<br>";

// Creating an object and initializing values using the constructor

$s1 = new Student("John Doe", 101);

$s1->display();
Faizan.M

?>

9. Develop a PHP program without using string functions:

(i) To calculate the length of a string


(ii) To count the number of words in a string

Ans:

php

<?php

// Function to calculate length of string

function stringLength($str) {

$length = 0;

while (isset($str[$length])) {

$length++;

return $length;

// Function to count number of words in string

function wordCount($str) {

$wordCount = 0;

$inWord = false;

for ($i = 0; isset($str[$i]); $i++) {

// Check if character is a space or not

if ($str[$i] != ' ' && !$inWord) {

$inWord = true;

$wordCount++;

} elseif ($str[$i] == ' ') {


Faizan.M

$inWord = false;

return $wordCount;

// Example string

$str = "Hello, this is a simple PHP program";

// Calculate and display string length

echo "String Length: " . stringLength($str) . "<br>";

// Count and display number of words

echo "Word Count: " . wordCount($str);

?>

10. Explain associative and multi-dimensional arrays.

Ans:

Associative Arrays

Associative arrays are very similar to numeric arrays in terms of functionality, but they
differ in their index. Associative arrays use strings as their index, allowing a strong
association between keys and values.

Example:

php

<?php

$salaries = array(

"mohammad" => 2000,

"Dinesh" => 1000,


Faizan.M

"Surabhi" => 500

);

echo "Salary of Arjun is ". $salaries['Arjun'] . "<br />";

echo "Salary of Dinesh is ". $salaries['Dinesh']. "<br />";

echo "Salary of Surabhi is ". $salaries['Surabhi']. "<br />";

echo "<pre>";

print_r($salaries);

echo "</pre>";

?>

Multidimensional Arrays

A multidimensional array contains one or more arrays. It has more than one dimension,
structured in rows and columns. Values in a multidimensional array are accessed using
multiple indexes.

Example:

php

<?php

$marks = array(

"Arjun" => array(

"physics" => 35,

"maths" => 30,

"chemistry" => 39

),

"Dinesh" => array(

"physics" => 30,

"maths" => 32,

"chemistry" => 29
Faizan.M

),

"Surabhi" => array(

"physics" => 31,

"maths" => 22,

"chemistry" => 39

);

// Accessing multi-dimensional array values

echo "Marks for Arjun in physics: " . $marks['Arjun']['physics'] . "<br />";

echo "Marks for Dinesh in maths: " . $marks['Dinesh']['maths'] . "<br />";

echo "Marks for Surabhi in chemistry: " . $marks['Surabhi']['chemistry'] . "<br />";

echo "<pre>";

print_r($marks);

echo "</pre>";

?>

11. State user-defined function and explain it with an example.

Ans:

A function is a named block of code that performs a specific task. PHP supports user-
defined functions, where the user can define their own functions.

A function doesn't execute when it is defined; it executes when it is called.

The syntax to create a PHP user-defined function:


A PHP user-defined function declaration starts with the keyword function as shown
below:

php

function functionName($arg1, $arg2, ... $argn)


Faizan.M

// Code to be executed inside a function

// return $val;

The syntax to call a PHP user-defined function:

php

$ret = functionName($arg1, $arg2, ... $argn);

Example:

php

<?php

// User-defined function definition

function printMessage() {

echo "Hello, How are you?";

// User-defined function call

printMessage();

?>

As shown in the above program, the printMessage() function is created using the
function keyword. The function prints the message "Hello, How are you?".
Later in the program, when the function is called using printMessage();, it prints the
message, as we can see in the output.

12. Explain the concept of constructor and destructor in detail.

Ans:
Same as before
Faizan.M

13. Write a program to create a PDF document in PHP.

Ans:
Same as before

14. Write a program to create an associative array in PHP.

Ans:
Same as before

15. Define function. How to define a user-defined function in PHP? Give an example.

Ans:
Same as before

16. Write a PHP script to sort any five numbers using the array function. *imp

Ans:

<?php $a = array(1, 8, 9, 4, 5); sort($a); foreach($a as $i) { echo $i.' '; } ?>

17. Explain any four string functions in PHP with an example.

Ans:
Same as before

18. Define Serialization.

Ans:

Definition:
Serializing an object means converting it to a bytestream representation that can be
stored in a file. Serialization in PHP is mostly automatic, it requires little extra work from
you, beyond calling the serialize() and unserialize() functions.

The serialize() function converts a storable representation of a value. To serialize data


means to convert a value to a sequence of bits so that it can be stored in a file, a
memory buffer, or transmitted across a network.

Syntax:
serialize(value);
Faizan.M

Example:

<?php $data = serialize(array("Red", "Green", 4044)); echo $data; ?>

Output:
a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;i:4044;}

19. Explain cloning an object.

Ans:

• The clone keyword is used in PHP to copy an object.

• It does a shallow copy, so any changes made in the cloned object will not affect
the original object.

• clone is a magic method in PHP. Magic methods are predefined in PHP and
start with “” (double underscore). They are executed in response to some events
in PHP.

Example:

<?php

// Creating an instance of the Animals class

$objAnimals = new Animals();

// Assigning values

$objAnimals->name = "Lion";

$objAnimals->category = "Wild Animal";

// Cloning the original object

$objCloned = clone $objAnimals;

$objCloned->name = "Elephant"; // Modifying the cloned object

// Printing the original object

echo "Original Object: ";

print_r($objAnimals);
Faizan.M

// Printing the cloned object

echo "Cloned Object: ";

print_r($objCloned);

?>

20. Define introspection.

Ans:

Introspection is the ability of a program to examine an object's characteristics, such as


its name, parent class (if any), properties, and methods. With introspection, we can
write code that operates on any class or object. We don't need to know which methods
or properties are defined when we write code; instead, we can discover that information
at runtime, which makes it possible for us to write generic debuggers, serializers,
profilers, etc.

Example:

<?php class parentclass { public $roll; public function par_function() {}} class childclass
extends parentclass {public $name; public function child_fun() {}} $obj = new
childclass(); // Class introspection print_r("parent class
exists:".class_exists('parentclass')); echo "<br> child class methods: ";
print_r(get_class_methods('childclass')); echo "<br> child class variables: ";
print_r(get_class_vars('childclass')); echo "<br> parent class variables: ";
print_r(get_class_vars('parentclass')); echo "<br> parent class: ";
print_r(get_parent_class('childclass')); // Object introspection echo "<br> is object: ";
print_r(is_object($obj)); echo "<br> object of a class: "; print_r(get_class($obj)); echo
"<br> object variables: "; print_r(get_object_vars($obj)); echo "<br> methods exist: ";
print_r(method_exists($obj, 'child_fun')); ?>

21. List types of inheritance.

Ans:

Inheritance is a mechanism of extending an existing class where a newly created or


derived class has all functionalities of an existing class along with its own properties
and methods.

• The parent class is also called a base class or super class. The child class is also
known as a derived class or a subclass.
Faizan.M

• Inheritance allows a class to reuse the code from another class without
duplicating it.

• Reusing existing codes serves various advantages. It saves time, cost, effort, and
increases a program’s reliability.

• To define a class that inherits from another class, you use the extends keyword.

Types of Inheritance:

1. Single Inheritance

2. Multilevel Inheritance

3. Multiple Inheritance

4. Hierarchical Inheritance

21. Define Introspection and explain it with a suitable example.

Ans:
Same as before

22. Write a program to demonstrate the concept of inheritance in PHP.

Ans:

php

<?php

// Parent class

class Vehicle {

public $brand;

// Method of parent class

function displayBrand() {

echo "Brand: " . $this->brand . "<br>";

// Child class inheriting from Vehicle


Faizan.M

class Car extends Vehicle {

public $model;

// Method of child class

function displayModel() {

echo "Model: " . $this->model . "<br>";

// Creating an object of the child class

$car = new Car();

$car->brand = "Toyota"; // Inherited property from parent

$car->model = "Camry"; // Child class property

$car->displayBrand(); // Parent class method

$car->displayModel(); // Child class method

?>

23. Explain method overriding with an example.

Ans:

Overriding occurs when a child class provides its own implementation of a method that
is already defined in the parent class. The method signature (name and parameters) in
the child class must match that of the parent class. By overriding a method, we can
customize the behavior of the method in the child class while retaining the same
method name.

To override a method in PHP, simply declare the method in the child class with the same
name as the parent class's method.

Example:

php
Faizan.M

class ParentClass {

function helloWorld() {

echo "Parent";

class ChildClass extends ParentClass {

function helloWorld() {

echo "\nChild";

$p = new ParentClass;

$c= new ChildClass;

$p->helloWorld();

$c->helloWorld();

24. Develop a PHP program for overriding.

Ans:

php

class shape {

// __call is magic function which accepts function name and arguments

function __call($name_of_function, $arguments) {

// It will match the function name

if ($name_of_function == 'area') {

switch (count($arguments)) {

// If there is only one argument, area of circle

case 1:
Faizan.M

return 3.14 * $arguments[0];

// If two arguments, then area is rectangle;

case 2:

return $arguments[0] * $arguments[1];

// Declaring a shape type object

$s = new Shape;

// Function call

echo $s->area(2);

echo "\n";

// Calling area method for rectangle

echo $s->area(4, 2);

?>

25. Write a PHP program on Introspection.

Ans:
Same as before

26. Define serialization and explain it with an example.

Ans:

i) Use of serialization.
Serializing an object means converting it to a bytestream representation that can be
stored in a file. Serialization in PHP is mostly automatic, it requires little extra work from
you, beyond calling the serialize() and unserialize() functions.
Faizan.M

Serialize():

• The serialize() function converts a storable representation of a value.

• The serialize() function accepts a single parameter which is the data we want to
serialize and returns a serialized string.

• Serialized data means a sequence of bits so that it can be stored in a file, a


memory buffer, or transmitted across a network connection link. It is useful for
storing or passing PHP values around without losing their type and structure.

Example:

php

<?php

$s_data = serialize(array('Welcome', 'to', 'PHP'));

print_r($s_data . "<br>");

$us_data = unserialize($s_data);

print_r($us_data);

?>

Output:
a:3:{i:0;s:7:"Welcome";i:1;s:2:"to";i:2;s:3:"PHP";}

Array ( [0] => Welcome [1] => to [2] => PHP )

27. Differentiate between implode and explode functions.


Faizan.M

Ans:

28. Explain the concept of cloning of an object.

Ans:
Same as before

29. Describe inheritance, overloading, overriding & cloning objects.

Inheritance allows classes to inherit properties and methods from a parent class,
overloading provides dynamic property and method handling, overriding enables
customization of inherited methods, and cloning creates copies of objects.

1. Inheritance: Inheritance is a fundamental concept in object-oriented


programming that allows classes to inherit properties and methods from another
class. In PHP, we can define a new class by extending an existing class using the
extends keyword. The new class is called the child or derived class, and the
existing class is called the parent or base class. The child class inherits all the
public and protected properties and methods of the parent class. It can also add
its own properties and methods or override the parent class's methods.

2. Overloading: In PHP, overloading refers to the ability to dynamically create


properties and methods in a class at runtime. There are two types of overloading:
a. Property Overloading: PHP provides the __set() and __get() magic methods to
Faizan.M

handle property overloading. When a property is accessed or modified that


doesn't exist or is inaccessible within the class, these methods are called,
allowing us to define custom logic for handling the property.
b. Method Overloading: PHP doesn't support method overloading in the
traditional sense (having multiple methods with the same name but different
parameters). However, we can use the __call() magic method to handle method
overloading. It gets called when a non-existent or inaccessible method is
invoked, giving the flexibility to handle the method dynamically.

3. Overriding: Overriding occurs when a child class provides its own


implementation of a method that is already defined in the parent class. The
method signature (name and parameters) in the child class must match that of
the parent class. By overriding a method, we can customize the behavior of the
method in the child class while retaining the same method name. To override a
method in PHP, simply declare the method in the child class with the same name
as the parent class's method.

4. Cloning Objects: Cloning an object in PHP allows us to create a duplicate of an


existing object. The clone is a separate instance of the class, but its properties
will initially have the same values as the original object. In PHP, we can clone an
object using the clone keyword followed by the object you want to clone. The
cloning process involves calling the __clone() magic method if it's defined in the
class. This method allows us to customize the cloning process by modifying the
properties of the cloned object if necessary.

You might also like